Hibernate一对一自动添加子对象

Hibernate One-To-One Adding child object automatically

我想使用休眠一对一关系在数据库中自动添加子对象。使用以下代码它不在地址 Table 中添加外键。

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);
        }
    }
当与一对一关系关联的实体具有相同的主键值时,使用

@PrimaryKeyJoinColumn。在这里你显然想使用经典外键,所以将 Address 实体中的映射更改为:

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