简体   繁体   English

如何防止hibernate在多对多映射中插入到一个表中

[英]how to prevent hibernate to insert into one table in many to many mapping

I'm creating user profile in which user can enter their interests where interest is predefined list user can not select out of this list. 我正在创建用户配置文件,其中用户可以输入他们感兴趣的预定义列表用户无法从此列表中选择。

i have User and Interest tables with primary key userId and interestId respectively. 我有User和Interest表分别带有主键userIdinterestId

             Table:User
-------------------------------------
        userId      userName
          1            aaaa
          2            bbbb
          3            cccc

and

           Table:Intrest
-------------------------------------
      interestId    interestName
          1            Sports
          2            Reading
          3            Music

Many to Many mapping table 多对多映射表

         Table:UserIntrest
-------------------------------------
        userId    interestId
          1            1
          1            2
          1            3

here is my code 这是我的代码

User.java User.java

@Entity
public class User {
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long userId;
    private String username;
    private String password;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(
        name="UserIntrest",
        joinColumns={ @JoinColumn(name="userId",referencedColumnName="userId") },
        inverseJoinColumns={ @JoinColumn(name="intrestId", referencedColumnName="intrestId") }
        )
    private List<Intrest> intrestList;

    ----- Getters Setters -----

Intrest.java Intrest.java

@Entity
@Table(name="intrest")
public class Intrest {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int intrestId;
    private String intrestName;

    public Intrest(String name){
        this.intrestName = name;
    }
----- Getters & Setters -----

ActionClass.java ActionClass.java

public class ActionClass extends ActionSupport {


    private User user;
    private List<String> intrestList;//for get list of intrest from jsp select tag
    private List<Intrest> intrestLst = new ArrayList<Intrest>();

    public String execute(){
        for(int i = 0;i<intrestList.size();i++){
            System.out.print(intrestLst.add(new Intrest(intrestList.get(i))));
        }
        user.setIntrestList(intrestLst);

        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();


        return SUCCESS;
    }

    ----- Getters & Setters -----

so when i run this it insert user in User table selected interests in Interest table and mapping in UserInterest Table 所以当我运行它时,它会在User表中插入用户选择兴趣表中的兴趣并在UserInterest表中映射

everything is ok but i don't need to insert interest in interest table because i already insert required interests. 一切都很好,但我不需要在兴趣表中插入兴趣,因为我已经插入了所需的兴趣。

Hibernate: insert into User (password, username) values (?, ?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into UserIntrest (userId, intrestId) values (?, ?)
Hibernate: insert into UserIntrest (userId, intrestId) values (?, ?)
Hibernate: insert into UserIntrest (userId, intrestId) values (?, ?)
Hibernate: insert into UserIntrest (userId, intrestId) values (?, ?)

I don't want to execute 我不想执行

Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)
Hibernate: insert into intrest (intrestName) values (?)

queries. 查询。

I search lots of for this problem but i can't find any solution. 我搜索了很多这个问题,但我找不到任何解决方案。

The problem is not in hibernate, but your code.. if you are doing new Interest(..) , hibernate will persist them in the DB, you should do something like: 问题不在于休眠,而在于你的代码..如果你正在做new Interest(..) ,hibernate会将它们保存在数据库中,你应该做类似的事情:

public class MyAction extends ActionSupport {
    private Long[] interestIds;

    public String execute() {

        // get interests with ids
        // set interests to user
        // save user

    }

}

First of all, you have to make sure that you have Getter and Setter for interestId , if you missed that "IDE doesn't show warning", you have to add them. 首先,你必须确保你有感兴趣的Getter和Setter,如果你错过了“IDE没有显示警告”,你必须添加它们。

then you have to do like this 那么你必须这样做

@Entity
class user{
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE})
@JoinTable(name="user_interest",joinColumns= {@JoinColumn(name="user_id", referencedColumnName = "id")},inverseJoinColumns= {@JoinColumn(name="interest_id", referencedColumnName = "id")})
private Set<Interest> interests= new HashSet<>();
 .
 .
 }
@Entity
@JsonIgnoreProperties({"users"})
class interest{
@ManyToMany(mappedBy="interests")
private List<User> users;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM