懒得初始化角色@Transactional和@LazyCollection(LazyCollectionOption.TRUE)的集合

时间:2017-01-17 04:46:29

标签: java spring hibernate

我知道这个问题之前曾多次被问到,但我不明白!

我无法编写HTTP消息:org.springframework.http.converter.HttpMessageNotWritableException:无法写入内容:无法懒惰地初始化角色集合:com.polytech.models.UserEntity.likesByUserId,无法初始化代理 - 没有会议;当我试图让用户喜欢时。

这是我的实体:

/**
 * Created by sydne on 11/01/2017.
 */
@Entity
@Table(name = "user", schema = "placetosee", catalog = "")
public class UserEntity {
    private Integer userId;
    private String nom;
    private String prenom;
    private String hashedPassword;
    private String email;
    private Date dateNaiss;
    private List<LikeEntity> likesByUserId ;
    private List<PreferencesEntity> preferencesByUserId;
    private List<VisiteEntity> visitesByUserId;

    @Id
    @Column(name = "user_id", nullable = false)
    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "nom", nullable = false, length = 50)
    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    @Basic
    @Column(name = "prenom", nullable = false, length = 50)
    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    @Basic
    @Column(name = "hashed_password", nullable = false, length = 1000)
    public String getHashedPassword() {
        return hashedPassword;
    }

    public void setHashedPassword(String hashedPassword) {
        this.hashedPassword = hashedPassword;
    }

    @Basic
    @Column(name = "email", nullable = false, length = 100)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "date_naiss", nullable = false)
    public Date getDateNaiss() {
        return dateNaiss;
    }

    public void setDateNaiss(Date dateNaiss) {
        this.dateNaiss = dateNaiss;
    }

    @JsonIgnore
    @LazyCollection(LazyCollectionOption.TRUE)
    @OneToMany( mappedBy = "byUserEntity",cascade = CascadeType.ALL)
    public List <LikeEntity> getLikesByUserId() {
        return likesByUserId;
    }

    public void setLikesByUserId(List<LikeEntity> likesByUserId) {
        this.likesByUserId = likesByUserId;
    }

    @JsonIgnore
    @LazyCollection(LazyCollectionOption.TRUE)
    @OneToMany( mappedBy = "byUserEntity",cascade = CascadeType.ALL)
    public List<PreferencesEntity> getPreferencesByUserId() {
        return preferencesByUserId;
    }

    public void setPreferencesByUserId(List<PreferencesEntity> preferencesByUserId) {
        this.preferencesByUserId = preferencesByUserId;
    }

    @JsonIgnore
    @LazyCollection(LazyCollectionOption.TRUE)
    @OneToMany( mappedBy = "byUserEntity",cascade = CascadeType.ALL)
    public List<VisiteEntity> getVisitesByUserId() {
        return visitesByUserId;
    }

    public void setVisitesByUserId(List<VisiteEntity> visitesByUserId) {
        this.visitesByUserId = visitesByUserId;
    }

    public void addPrererence (PreferencesEntity preference) {
        getPreferencesByUserId().add(preference);
    }

    public void deletePreference (PreferencesEntity preference ) {
        getPreferencesByUserId().remove(preference);
    }
}

和我的喜欢

    @Entity
@Table(name = "like", schema = "placetosee", catalog = "")
public class LikeEntity implements Serializable {


    @EmbeddedId
    private LikeEntityPK id;

    private Byte isLiking;

    public LikeEntityPK getId() {
        return id;
    }

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

    //bi-directional many-to-one association to Lieu
    @ManyToOne
    @JoinColumn(name="lieu_id",referencedColumnName ="lieu_id" ,insertable =false,updatable = false, nullable = false)
    private LieuEntity byLieuEntity;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="user_id", referencedColumnName ="user_id", insertable =false,updatable = false, nullable = false)
    private UserEntity byUserEntity;


    @Basic
    @Column(name = "is_liking", nullable = false)
    public Byte getIsLiking() {
        return isLiking;
    }

    public void setIsLiking(Byte isLiking) {
        this.isLiking = isLiking;
    }

    public void setLieuByLieuId(LieuEntity lieuByLieuId) {
        this.byLieuEntity= lieuByLieuId;
    }
}

这是我的控制器:

    @RequestMapping(value="/like")
    @RestController
    @Transactional
    public class LikeController {

        @Autowired
        public LikeDAO _likeDao ;

        // localhost:8080/like/getlikes?user_id=2
        @RequestMapping(value = "/getlikes")
        @Produces(MediaType.APPLICATION_JSON)
        public @ResponseBody List  <LikeEntity> getUserLikes(@RequestParam int user_id) {
           return _likeDao.getLikeByUserId(user_id);
        }

}

最后我的DAO:

@Service
@Transactional
public class LikeDAO {

    @Autowired
    private LocalSessionFactoryBean _sessionFactory;

    @Autowired
    public UserDAO _userDao;

    private Session getSession() {
        return _sessionFactory.getObject().getCurrentSession();
    }


    public List<LikeEntity> getAll() {
        return getSession().createQuery("from LikeEntity ").list();
    }


    public List<LikeEntity> getLikeByUserId (int user_id) {
       return _userDao.getById(user_id).getLikesByUserId();
    }

    public List<LikeEntity> getLikesForUser (int user_id) {
        //return getSession().
    }

    public void save(LikeEntity like) {
        getSession().save(like);

    }

    public LikeEntity getById(int user_id, int lieu_id) {
        LikeEntityPK id = new LikeEntityPK();
        id.setUserId(user_id);
        id.setLieuId(lieu_id);
        return getSession().get(LikeEntity.class, id);
    }

    public void delete (LikeEntity like) {
        getSession().delete(like);
    }
}

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

默认情况下,对于所有集合和地图对象,提取规则为(JPA)FetchType.LAZY (Hibernate @LazyCollection)@OneToMany@ManyToMany关系不会获取相关对象(集合)。您必须初始化DAO中的相关实体或使用FetchMode查询它们,如@Fetch(FetchMode.JOIN)等...但是如果您使用连接查询,它将复制您的结果ofc,因此您必须区分结果。

答案 1 :(得分:0)

在Spring中,你不能在Spring MVC Controller中使用@Transactional。 - 请点击此处Spring Forum

你必须实现一个接口,Spring可以将其用作代理接口 - 如下所示

@Controller
public interface LikeInterface {
   List<LikeEntity> getUserLikes(int user_id);
}

@RestController
@RequestMapping(value="/like")
public class LikeController implements LikeInterface{

    @RequestMapping(value = "/getlikes")
    @Produces(MediaType.APPLICATION_JSON)
    public @ResponseBody List  <LikeEntity> getUserLikes(@RequestParam int user_id) {
       return _likeDao.getLikeByUserId(user_id);
    }
}