Hibernate: More than one relationship using the same join column
I'm using a legacy database schema with composite keys. I have an entity with two relationships and one of the join columns is shared.
For examp开发者_如何学编程le, Let's say i have a Student entity with two relationships Department and Course. Department uses dept_code column while Course uses dept_code and course_code colum. The domain model is such that a student might belong to a department and not opted for a course yet or the student might have chosen both department and course. This is how the hibernate mapping looks like:
<many-to-one class="Department" name="department">
<column name="dept_code"/>
</many-to-one>
<many-to-one class="Course" name="course>
<column name="dept_code"/>
<column name="course_code"/>
</many-to-one>
The problem is Hibernate does not allow this mapping unless one of the relationships is marked readonly using insert=false and update=false.
Is there a way to have both relationships writable?
Could you try the following
1) Set the not-null property on the dept_code and see what happens (Is that acceptable?)
2) Set the department to be read only and the course to be write and in the setDepartment create a course object with course_code null of the existing course code and actually use the setCourse and see if updates go fine ?
I understand that you have a legacy DB and therefore probably can't change the tables? But if possible I would insert a surrogate key or a new join table.
If you don't have that option you always could write your own load and persist SQL. Take a look at the < loader >, < sql-insert >, < sql-delete > and < sq-update > mapping elements. See https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/querysql.html chapter 13.3. and following.
As a third option you could just map your entities without that connection and do the CRUD methods yourself: write the load, save, update and persist methods yourself and handle the connections between the entities manually. That could be done transaprent to your client code. The caller would just use the setDepartment and getDepartment methods and your DAO (or whatever other concept you are using) would handle the rest.
Btw: There is a helpful chapter in the JPA/Hibernate Book from Manning for that kind of problems ("Java Persistence with Hibernate" Chapter 8 - Legacy Databases and custom SQL).
精彩评论