gpt4 book ai didi

java - Spring引导+ Jersey API+JPA : failed to lazily initialize a collection of role

转载 作者:行者123 更新时间:2023-12-02 12:10:43 25 4
gpt4 key购买 nike

我是使用 spring boot + jersey api + JPA 的新手。我有三个使用一对多双向映射的实体。当我使用 spring boot + jersey api+ JPA 时,出现错误:无法延迟初始化角色集合:com.kavinaam.GSTbilling.entity.Country.states,无法初始化代理 - 无 session (通过引用链:java.util.ArrayList[0]->com.kavinaam. GSTbilling.entity.City["states"]->com.kavinaam.GSTbilling.entity.States["countyId"]->com.kavinaam.GSTbilling.entity.Country["states"])

我已经添加了我的实体、 dao 、服务和端点。

@Entity
@Table(name="country")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;
@Column(name="countryName")
private String countryName;

@OneToMany(mappedBy = "countyId",cascade = CascadeType.ALL)
private Set<States> states;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getCountryName() {
return countryName;
}

public void setCountryName(String countryName) {
this.countryName = countryName;
}

public Set<States> getStates() {
return states;
}

public void setStates(Set<States> states) {
this.states = states;
}

}

我的状态类:

@Entity
@Table(name="states")
public class States implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;

@ManyToOne
@JoinColumn(name="countyId")
private Country countyId;

@Column(name="stateName")
private String stateName;

@OneToMany(mappedBy = "states", cascade = CascadeType.ALL)
private Set<City> city;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}


public Country getCountyId() {
return countyId;
}
public void setCountyId(Country countyId) {
this.countyId = countyId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Set<City> getCity() {
return city;
}
public void setCity(Set<City> city) {
this.city = city;
}
}

我的城市类别:

@Entity
@Table(name="cities")
public class City implements Serializable{

/**
*
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;

@ManyToOne
@JoinColumn(name="stateId")
private States states;

@Column(name="cityName")
private String cityName;

@Column(name="zip")
private String zip;


public void setId(int id) {
this.id = id;
}
public void setZip(String zip) {
this.zip = zip;
}


public States getStates() {
return states;
}
public void setStates(States states) {
this.states = states;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getZip() {
return zip;
}
public int getId() {
return id;
}

}

我的 DAO:

@Transactional
@Repository
public class GSTCityDAO implements IGSTCityDAO {

@PersistenceContext
private EntityManager entityManager;

//@SuppressWarnings("unchecked")
@Override
public List<City> getAllCities() {
//Session session = sessionFactory.getCurrentSession();
String hql = "FROM City as ct ORDER BY ct.id";
List<City> l = entityManager.createQuery(hql,City.class).getResultList();

return l;
}

@Override
public City getCityById(int cityId) {
return entityManager.find(City.class, cityId);
}

@SuppressWarnings("unchecked")
@Override
public List<City> getCityByStateId(States stateId) {
String getcitybystate = " FROM City as c WHERE c.states = ?";
return (List<City>) entityManager.createQuery(getcitybystate).setParameter(1, stateId).getResultList();
}

@Override
public void addCity(City city) {
entityManager.persist(city);

}

@Override
public void updateCity(City city) {
City cityctl = getCityById(city.getId());
cityctl.setCityName(city.getCityName());
cityctl.setZip(city.getZip());
cityctl.setStates(city.getStates());
entityManager.flush();
}

@Override
public void deleteCity(int cityId) {
entityManager.remove(getCityById(cityId));
}

@Override
public boolean cityExists(String name, String zip) {
String hql = "FROM City WHERE cityName = ? and zip = ?";
int count = entityManager.createQuery(hql).setParameter(1,name).setParameter(2, zip).getResultList().size();
return count > 0 ? true : false;
}

}

服务:

@Service
public class GSTCityService implements IGSTCityService {

@Autowired
private IGSTCityDAO cityDAO;

@Override
public List<City> getAllCities() {
List<City> l = cityDAO.getAllCities();
Hibernate.initialize(l);
return l;
}

public List<City> getCityByStateId(States stateId) {
return cityDAO.getCityByStateId(stateId);
}

@Override
public City getCityById(int cityId) {
City city = cityDAO.getCityById(cityId);
return city;
}

@Override
public synchronized boolean addCity(City city) {
if(cityDAO.cityExists(city.getCityName(), city.getZip())){
return false;
}else{
cityDAO.addCity(city);
return true;
}
}

@Override
public void updateCity(City city) {
cityDAO.updateCity(city);
}

@Override
public void deleteCity(int cityId) {
cityDAO.deleteCity(cityId);

}

}

终点:

@Component
@Path("/")
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
@Autowired
private IGSTCityService cityService;

@GET
@Path("/hi")
@Produces(MediaType.APPLICATION_JSON)
public Response hello(){
return Response.ok("Hello GST").build();
}

@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllDate(){
List<City> list = cityService.getAllCities();
for(City city: list){
System.out.println(city);
}
return Response.ok(list).build();
}

@GET
@Path("/test/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllDateBySome(@PathParam("id") Integer id){
States state = new States();
state.setId(id);
List<City> list = cityService.getCityByStateId(state);
return Response.ok(list).build();
}

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDataById(@PathParam("id")Integer id){
City citl = cityService.getCityById(id);
return Response.ok(citl).build();
}

@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response addData(City city){
boolean isAdded = cityService.addCity(city);
if(!isAdded){
return Response.status(Status.CONFLICT).build();
}
return Response.created(URI.create("/gst/"+ city.getId())).build();
}

@PUT
@Path("/update")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCountry(City city){
cityService.updateCity(city);
return Response.ok(city).build();
}

@DELETE
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteCountry(@PathParam("id")Integer id){
cityService.deleteCity(id);
return Response.noContent().build();
}

}

我正在使用 import org.springframework.transaction.annotation.Transactional; DAO 中的跨国公司。另外,我无法使用 @PersistenceContext(type=PersistenceContextType.EXTENDED) 和获取类型 Eager,因为我收到 超出最大堆栈大小

错误

最佳答案

我通过在 OneToMany 关系上使用 @JsonBackReference 解决了这个问题。问题在于序列化和反序列化。"使用 @JsonManagedReference 注解注释的属性被正常处理(正常序列化,反序列化不需要特殊处理),而使用 @JsonBackReference 注解注释的属性不被序列化;并且在反序列化期间,其值被设置为具有“托管”的实例(转发)链接。”

关于java - Spring引导+ Jersey API+JPA : failed to lazily initialize a collection of role,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com