Hibernate One-To-One自动添加子对象

时间:2016-03-17 11:04:18

标签: java database hibernate one-to-one

我想使用hibernate One to One关系在DB中自动添加子对象。使用以下代码它不在地址表中添加外键。

public class Address implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "address")
    private String address;
    @OneToOne(cascade = CascadeType.ALL) 
    @PrimaryKeyJoinColumn(name = "p_id", referencedColumnName = "id")
    private Person pId;

    Getters And Setters
}

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "birthdate")
    @Temporal(TemporalType.TIMESTAMP)
    private Date birthdate;
    @Column(name = "email")
    private String email;
    @Column(name = "mobile")
    private BigInteger mobile;
    @Column(name = "name")
    private String name;
    @OneToOne(mappedBy = "pId", cascade = CascadeType.ALL)
    private Address address;

    Getters And Setters
}

这是主要方法

public static void main(String[] args) 
    {
        try
        {
            Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            Person person = new Person();
            person.setBirthdate(new Date());
            person.setEmail("hjhjhjhj@gmail.com");
            person.setMobile(new BigInteger("44444444"));
            person.setName("kjkljkljkj");
            Address address = new Address();
            address.setAddress("jkhkjhkj");
            address.setPId(person);
            person.setAddress(address);
            session.save(person);
//            session.save(address);
            transaction.commit();
            session.flush();
            session.close();
            System.out.println("Success...");
        }
        catch(Exception e)
        {
            e.printStackTrace(System.out);
        }
    }

1 个答案:

答案 0 :(得分:0)

当与一对一关系关联的实体具有相同的主键值时,使用

@PrimaryKeyJoinColumn。在这里,您显然希望使用经典外键,因此将Address实体中的映射更改为:

@OneToOne(cascade = CascadeType.ALL) 
@JoinColumn(name = "p_id")
private Person pId;