如何在使用hibernate多对多注释时防止在db中插入重复记录

时间:2013-02-11 19:18:06

标签: java hibernate

添加用户工作正常。 面临的问题是 正在添加任务n相应的用户也被添加,但“每次添加新用户”即使他存在于Users表中。这导致了Bridge表中的taskid n userid不匹配。任何人都可以帮助我......这真的是......我的POJOS用户n任务。调用是由JSP文件完成的......等待它的任何帮助!!!!

@Entity
@Table(name ="Tasks")
public class Tasks implements Serializable
{
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "t_Id")
private int Id;
@Column (name = "t_Name")
private String TaskName;
@Column (name = "t_Details")
private String TaskDetails;
@Column (name = "t_Status")
private int TaskStatus;
@ManyToMany(targetEntity = org.Users.class, fetch = FetchType.LAZY, cascade =       {CascadeType.ALL, CascadeType.PERSIST})
//@Cascade({ CascadeType.ALL})
@JoinTable(name = "user_Tasks", joinColumns = {@JoinColumn(name = "t_Id")},  inverseJoinColumns = {@JoinColumn(name = "u_Id")})
private Set <Users> users = new HashSet<Users>(0);

public Tasks(){}
public Tasks(String TaskName) {
    this.TaskName = TaskName;
}

public Tasks( String TaskName, String TaskDetails, int TaskStatus) {
    this.TaskName = TaskName;
    this.TaskDetails = TaskDetails;
    this.TaskStatus = TaskStatus;
}

public Tasks(String TaskName, String TaskDetails, int TaskStatus, Set<Users> users)
{
    this.TaskName = TaskName;
    this.TaskDetails = TaskDetails;
    this.TaskStatus = TaskStatus;
    this.users = users;
}
public int getId() {
    return Id;
}
 public void setId(int Id) {
    this.Id = Id;
}
public String getTaskName() {
    return TaskName;
}
 public void setTaskName(String TaskName) {
    this.TaskName = TaskName;
}
public String getTaskDetails() {
    return TaskDetails;
}
public void setTaskDetails(String TaskDetails) {
    this.TaskDetails = TaskDetails;
}
 public int getTaskStatus() {
    return TaskStatus;
}
public void setTaskStatus(int TaskStatus) {
    this.TaskStatus = TaskStatus;
}
public Set<Users> getUsers() {
    return users;
}
public void setUsers(Set<Users> users) {
    this.users = users;
}

}
@Entity
@Table(name = "USERS")
public class Users implements Serializable {
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "u_Id")
private int Id;
@Column (name ="u_Name")        
private String Name;
@Column (name ="u_Username")
private String Username;
@Column (name="u_Password")
private String password;
@ManyToMany(targetEntity =org.Tasks.class, fetch = FetchType.LAZY, mappedBy="users", cascade ={CascadeType.ALL, CascadeType.PERSIST})
// @Cascade({CascadeType.ALL})
@JoinTable(name = "user_Tasks", joinColumns = {@JoinColumn(name = "u_Id")}, inverseJoinColumns = {@JoinColumn(name = "t_Id")})
private Set<Tasks> task = new HashSet<Tasks>();
public Users(){}
public Users(String Name) {
    this.Name = Name;
}

public int getId() {
    return Id;
}
public void setId(int Id) {
    this.Id = Id;
}
public String getName() {
    return Name;
}
 public void setName(String Name) {
    this.Name = Name;
}
public String getUsername() {
    return Username;
}
public void setUsername(String Username) {
    this.Username = Username;
}
public String getPassword() {
    return password;
}  
public void setPassword(String password) {
    this.password = password;
}

public Set<Tasks> getTask() {
    return task;
}

public void setTask(Set<Tasks> task) {
    this.task = task;
}
@Override
public int hashCode() {
    int hash = 7;
    hash = 19 * hash + (this.Name != null ? this.Name.hashCode() : 0);
    hash = 19 * hash + (this.Username != null ? this.Username.hashCode() : 0);
    hash = 19 * hash + (this.password != null ? this.password.hashCode() : 0);
    return hash;
 }
 @Override
 public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Users other = (Users) obj;
    if ((this.Name == null) ? (other.Name != null) : !this.Name.equals(other.Name)) {
        return false;
    }
    if ((this.Username == null) ? (other.Username != null) : !this.Username.equals(other.Username)) {
        return false;
    }
    if ((this.password == null) ? (other.password != null) : !this.password.equals(other.password)) {
        return false;
    }
    return true;
 }

}

public class ManageTasks

  public static void main(String arg[])
  {
  try
  {
  SessionFactory factory = new AnnotationConfiguration().configure().addPackage("org").addAnnotatedClass(Tasks.class).addAnnotatedClass(Users.class).buildSessionFactory();        
  }catch(Exception e)
  {
  System.out.println(e);
  }

  }
  public Integer addTasks(String TaskName, String TaskDetails, int  TaskStatus, Set use)
   {
  SessionFactory factory = new AnnotationConfiguration().configure().addPackage("org").addAnnotatedClass(Tasks.class).addAnnotatedClass(Users.class).buildSessionFactory();
  Session session = factory.openSession();
  Transaction tx = null;
  Integer taskID = null;
  try
  {  
      tx = session.beginTransaction();  
      Tasks task = new Tasks(TaskName, TaskDetails, TaskStatus);
      task.setUsers(use);

      session.save(task);
      tx.commit();      
  }catch(HibernateException e)
  {
  if(tx!=null) tx.rollback();
  e.printStackTrace();
  }
  finally
          {
              session.close();
          }    
  return taskID;
  }      
  public void addUser(String name, String username, String password)
{
   SessionFactory factory = new AnnotationConfiguration().configure().addPackage("org").addAnnotatedClass(Users.class).
                   buildSessionFactory();
    Session session = null;
    session = factory.openSession();
    Transaction tx = null;
    Integer userID = null;  
  try
  {
     tx = session.beginTransaction();
     Users user = new Users();
     user.setName(name);
     user.setUsername(username);
     user.setPassword(password);
     userID = (Integer) session.save(user); 
     tx.commit();
  }catch (HibernateException e)
  {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
  }
  finally
  {
     session.close(); 
  }

 }   

这是AddTask调用代码

String taskname = request.getParameter("taskname");
String taskdetails = request.getParameter("taskdetails");
tring user1 = request.getParameter("user1");
String user2 = request.getParameter("user2");
String user3 = request.getParameter("user3");
Set <Users> user = new HashSet <Users>();
user.add(new Users(user1));
user.add(new Users(user2));
user.add(new Users(user3));
nt TaskStatus;
if(taskname == null && taskdetails == null)
TaskStatus = 0;
else
TaskStatus = 1;

ManageTasks mt = new ManageTasks();
mt.addTasks(taskname, taskdetails, TaskStatus, user);
out.println("Sucessfully added!!");

1 个答案:

答案 0 :(得分:0)

创建任务时,您需要添加从DB中检索到的已经拥有ID的用户。这样,Hibernate不会插入新用户,只会在持久化任务实体时仅插入连接表中的条目。

在创建新任务的代码中,您必须找到现有用户而不是创建新用户。所以你应该编写一个方法findUserByName(String name)来从DB中检索用户并替换:
user.add(new Users(user1));
搭配:
user.add(findUserByName(user1));