I have a parent class 'Task' and it has child 'Tag' in it. where i want tag name(see Tag class) to be unique, but when i am trying to saving parent class a new child record is creating. How can i eliminate duplicates child records.
Here is my code
Task Class
Code:
@Entity
@Table(name="tasks")
public class TaskDTO {
...
...
@ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable( name = "task_tags",joinColumns = { @JoinColumn(name = "taskId") }, inverseJoinColumns = { @JoinColumn(name = "tagId") })
private List<TagDTO> tags = new ArrayList<TagDTO>();
}
Tag Class
Code:
@Entity
@Table(name="tags")
public class TagDTO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "tagId")
private int tagId;
@Column(name = "tagName")
private String tagName;
}
TaskDAOImpl
Code:
@Repository("taskDAOImpl")
public class TaskDAOImpl implements TaskDAO {
@Override
public Integer saveTask(TaskDTO taskDTO) {
Integer identifier = null;
try {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
..........
..........
identifier = (Integer) session.save(taskDTO);
return identifier;
} catch (Exception ex) {
logger.error("unable to save task ", ex);
}
return null;
}
When i saved tags i get this in my database.
Code:
mysql> select * from tags;
+-------+---------+
| tagId | tagName |
+-------+---------+
| 1 | java |
| 2 | java |
+-------+---------+
2 rows in set (0.00 sec)
mysql> select * from task_tags;
+--------+-------+
| taskId | tagId |
+--------+-------+
| 69 | 1 |
| 70 | 2 |
+--------+-------+
2 rows in set (0.00 sec)
i want to eliminate that tagName saved two times.
But i want some thing like this
Code:
mysql> select * from tags;
+-------+---------+
| tagId | tagName |
+-------+---------+
| 1 | java |
+-------+---------+
2 rows in set (0.00 sec)
mysql> select * from task_tags;
+--------+-------+
| taskId | tagId |
+--------+-------+
| 69 | 1 |
| 70 | 1 |
+--------+-------+
2 rows in set (0.00 sec)
Please help me on this. Thanks all in advance.