2 u012352861 u012352861 于 2017.01.15 15:05 提问

关于Hibernate有连接双向1-1关联映射

我用的是Hibernate5.2.6版本,是用注解实现的映射,三个类代码如下,运行后数据库能生成三张表,但表没有数据,而且控制台会报错,请问这种错误是版本的原因吗?

@Entity
@Table(name = "person")
public class Person
{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String  name;

    @OneToOne(targetEntity = Address.class)
    @JoinTable(name = "person_addr", 
        joinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id", unique = true),
        inverseJoinColumns = @JoinColumn(name = "address_id", referencedColumnName = "addr_id", unique = true))
    private Address address;

    public void setId(Integer id)               { this.id = id; } 
    public void setName(String name)            { this.name = name; } 
    public void setAddress(Address address)     { this.address = address; }

    public Integer getId()          { return id; } 
    public String getName()         { return name; } 
    public Address getAddress()     { return address; } 

}
 @Entity
@Table(name = "addr_inf")
public class Address
{
    @Id @Column(name = "addr_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String  addrDetail;

    @OneToOne(targetEntity = Person.class)
    @JoinTable(name = "person_addr", 
            joinColumns = @JoinColumn(name = "address_id", referencedColumnName = "addr_id", unique = true),
            inverseJoinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id", unique = true))
    private Person person;

    public Address()                                { }
    public Address(String addrDetail)               { this.addrDetail = addrDetail; }

    public void setId(Integer id)                   { this.id = id; }  
    public void setAddrDetail(String addrDetail)    { this.addrDetail = addrDetail; } 
    public void setPerson(Person person)            { this.person = person; }

    public Integer getId()          { return id; }
    public String getAddrDetail()   { return addrDetail; }  
    public Person getPerson()       { return person; } 
}
 public class Test
{
    public static void main(String[] args) throws Exception
    {
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sf = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sf.openSession();
        Transaction transaction = session.beginTransaction();

        Person p = new Person();
        p.setName("aaa");

        Address a = new Address("上海");
        p.setAddress(a);
        session.persist(a);
        session.save(p);

        transaction.commit();
        session.close();
        sf.close();
    }
}

1个回答

caozhy
caozhy   Ds   Rxr 2017.01.15 15:13
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!