Java 弹簧&x2B;hibernate Pb在加载对象时从DB收集数据
我有两个像这样的A班和B班Java 弹簧&x2B;hibernate Pb在加载对象时从DB收集数据,java,spring,hibernate,jpa-2.0,spring-data-jpa,Java,Spring,Hibernate,Jpa 2.0,Spring Data Jpa,我有两个像这样的A班和B班 @Entity @Table public class A implements Serializable { @Id @Column @GeneratedValue ( strategy = GenerationType.IDENTITY ) private Long idA; @Column private String nomA; @OneToMany ( mappedBy = "a" ) private
@Entity
@Table
public class A implements Serializable {
@Id
@Column
@GeneratedValue ( strategy = GenerationType.IDENTITY )
private Long idA;
@Column
private String nomA;
@OneToMany ( mappedBy = "a" )
private Collection < B > liste;
..........
}
@Entity
@Table
public class B implements Serializable {
@Id
@Column
@GeneratedValue ( strategy = GenerationType.IDENTITY )
private Long idB;
@Column
private String nomB;
@ManyToOne
@JoinColumn ( name = "idA" )
private A a;
...........
}
这是B刀
@Repository
@Transactional
public class BdaoImpl implements Bdao {
@PersistenceContext ( type = PersistenceContextType.EXTENDED )
private EntityManager em;
@Override
public Long addB ( B b ) {
em.persist ( b );
return b.getIdB ( );
}
@Override
public B getB ( Long idB ) {
// TODO Auto-generated method stub
return em.find ( B.class , idB );
}
}
现在是服务时间
@Service
@Transactional
public class AserviceImpl implements Aservice {
@Autowired
private Adao dao;
@Override
public Long ajouterA ( A a ) {
// TODO Auto-generated method stub
return dao.addA ( a );
}
@Override
public A retournerA ( Long idA ) {
// TODO Auto-generated method stub
return dao.getA ( idA );
}
.......
}
B服务
@Service
@Transactional
public class BserviceImpl implements Bservice {
@Autowired
private Bdao dao;
@Override
public Long ajouterB ( B b ) {
// TODO Auto-generated method stub
return dao.addB ( b );
}
@Override
public B retournerB ( Long idb ) {
// TODO Auto-generated method stub
return dao.getB ( idb );
}
....
}
当我使用此代码测试它时:
ApplicationContext ctx = new ClassPathXmlApplicationContext (
"spring.xml" );
Aservice aservice = ( Aservice ) ctx.getBean ( "aserviceImpl" );
Bservice bservice = ( Bservice ) ctx.getBean ( "bserviceImpl" );
A a = new A ( "obj A1" );
B b1 = new B ( "obj B1" );
b1.setA ( a );
B b2 = new B ( "obj B2" );
b2.setA ( a );
Long Id = aservice.ajouterA ( a );
bservice.ajouterB ( b1 );
bservice.ajouterB ( b2 );
System.out.println ( ">>>>>>>> "
+ aservice.retournerA ( Id ).toString ( ) );
我得到了一个[idA=1,nomA=obja1,liste=null]
我想知道为什么我的列表是空的在保存A之前,必须将B项添加到类中的集合中
a.getListe().add(b1);
a.getListe().add(b2);
然后打电话
Long Id = aservice.ajouterA ( a );
其原因是休眠第一级缓存即会话缓存。它缓存仅在此会话生存期内连接到会话的所有实体 所以如果你打电话
em.find ( A.class , idA );
然后hibernate将返回缓存的A,它没有分配B
现在您有两个选择:
em.refresh(a);
这样,hibernate就可以从数据库中重新加载。但是,正如@HarshPoddar已经指出的那样,您还需要在与B的关系上声明fetchType.EAGERa.getListe().add(b1);
a.getListe().add(b2);
正如@laugther已经发布的那样我会和你一起去。选项。尝试
@OneToMany(mappedBy=“a”,fetch=FetchType.EAGER)
结果仍然相同
a.getListe().add(b1);
a.getListe().add(b2);