spring data jpa 一对多关系怎么配置 20C
//实体类1
 @Entity
@Table(name = "t_user")
//@Data
//@ToString(exclude = {"role"})
public class TUser {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Integer id;
    private String username;
    private String password;
    private String email;
    private Integer sex;//性别,0.1.2(男,女,未知)
    private Date last_login;
    private Date create_time;//创建时间
    private Date update_time;//修改时间
    private String phone;//电话
    private String photo;//图片地址
    private Integer status;//状态,0正常,1禁止

    @ManyToOne(cascade=CascadeType.PERSIST)//cascade=CascadeType.PERSIST(开启级联操作)
    @JoinColumn(name="roles_id")
    private TRole role;
    }

    //实体类2
    @Entity
@Table(name = "t_role")
//@Data
public class TRole {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Integer id;
    private String memo;
    private String r_name;
    private Date ctime;
    private Date update_time;



    @OneToMany(mappedBy="role")
    private Set<TUser> set = new HashSet<>();
}
//dao层
public interface TUserDao extends JpaRepository<TUser, Integer>{

}

//测试代码

@Autowired
    private TUserDao tuserDao;



    //添加
    @Test
    public void add() {

        TRole role = new TRole();
        role.setCtime(new Date());
        role.setMemo("注解");
        role.setR_name("管理员");
        role.setUpdate_time(new Date());


        TUser tUser = new TUser();
        tUser.setCreate_time(new Date());
        tUser.setEmail("1655@qa.com");
        tUser.setLast_login(new Date());
        tUser.setPassword("123456");
        tUser.setPhone("www");
        tUser.setPhoto("www.as");
        tUser.setSex(0);
        tUser.setStatus(0);
        tUser.setUpdate_time(new Date());
        tUser.setUsername("nichen");

        role.getSet().add(tUser);
        tUser.setRole(role);


        tuserDao.save(tUser);
    }


    //查询
    @Test
    public void findAll() {
        List<TUser> findAll = tuserDao.findAll();
        for (TUser tUser : findAll) {
            System.out.println("tUser:"+tUser);
        }
        System.out.println("size:"+findAll.size());
    }


    这代码插入是可以的,查询就会有问题。
测试中的查询的错误:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.simulation.admin.model.TRole.set, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:299)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at com.simulation.admin.model.TRole.toString(TRole.java:99)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at com.simulation.admin.model.TUser.toString(TUser.java:166)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at com.simulation.admin.SimulationApplicationTests.findAll(SimulationApplicationTests.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

如果是用服务的接口访问的错误:java.lang.StackOverflowError: null
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:136) ~[na:1.8.0_144]
    at java.sql.Timestamp.toString(Timestamp.java:302) ~[na:1.8.0_144]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:165) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144]
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na]
    at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144]
    at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na]

1个回答

一、@OneToOne关系映射
JPA使用@OneToOne来标注一对一的关系。

实体 People :用户。

实体 Address:家庭住址。

People 和 Address 是一对一的关系。

这里用两种方式描述JPA的一对一关系。

一种是通过外键的方式(一个实体通过外键关联到另一个实体的主键);

另外一种是通过一张关联表来保存两个实体一对一的关系。

1、通过外键的方式

people 表(id,name,sex,birthday,address_id)

address 表(id,phone,zipcode,address)

People.java@Entity
public class People {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;//id
@Column(name = "name", nullable = true, length = 20)
private String name;//姓名
@Column(name = "sex", nullable = true, length = 1)
private String sex;//性别
@Column(name = "birthday", nullable = true)
private Timestamp birthday;//出生日期
@OneToOne(cascade=CascadeType.ALL)//People是关系的维护端,当删除 people,会级联删除 address
@JoinColumn(name = "address_id", referencedColumnName = "id")//people中的address_id字段参考address表中的id字段
private Address address;//地址
关联的实体的主键一般是用来做外键的。但如果此时不想主键作为外键,则需要设置referencedColumnName属性。当然这里关联实体(Address)的主键 id 是用来做主键,所以这里第20行的 referencedColumnName = "id" 实际可以省略。
Address.java

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;//id
@Column(name = "phone", nullable = true, length = 11)
private String phone;//手机
@Column(name = "zipcode", nullable = true, length = 6)
private String zipcode;//邮政编码
@Column(name = "address", nullable = true, length = 100)
private String address;//地址
//如果不需要根据Address级联查询People,可以注释掉
// @OneToOne(mappedBy = "address", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
// private People people;
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐