ibatis-user-java mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ingmar Lötzsch <iloetz...@asci-systemhaus.de>
Subject Re: 2 Way 1-1 relationship
Date Wed, 21 Jan 2009 11:38:48 GMT
Petr V. schrieb:
> I want to have two way relationship like Teacher contains reference of
> Student and Student contains reference of Teacher. Is it even possible
> in iBatis ?
> 
> class Teacher {
>      Student sid;
>      ....
> }
> 
> class Student {
>      Teacher teacher;
>      ....
> }
> 
> 
> I wrote the following SQL config file and as expected I got stack over
> flow due to recursion.(Map referring each other)
> 
> <resultMap id="TeacherResultMap99" class="Teacher" groupBy="id" >
>     <result property="id"   column="tea_id"/>
>     <result property="name" column="tea_name" />
>     <result property="sid" resultMap="JOB.StudentResultMap99"/>
> </resultMap>
> 
> <resultMap id="StudentResultMap99" class="Student" >
>   <result property="id" column="stu_id"/>
>   <result property="name" column="stu_Name"/>
>   <result property="teacher" resultMap="JOB.TeacherResultMap99"/>   
> </resultMap>
> 
> 
> <select id="findStudent"  parameterClass="int"
> resultMap="StudentResultMap99">
>     select t.id as tea_id , t.name as tea_name , s.id as stu_id, s.name
> as stu_Name , s.tid as stu_tid from Teacher t left join student s on
> t.id = s.tid where s.id = #value#
> </select>

SELECT
	t.id AS tea_id,
	t.name AS tea_name,
	s.id AS stu_id,
	s.name AS stu_name,
	s.tid AS stu_tid
FROM teacher t
LEFT JOIN student s ON t.id = s.tid
WHERE s.id = #value#

I don't understand, why you use a LEFT JOIN to table student. You
provide the ID of the student as a parameter. If there exists a
corresponding row, you get a result, if not, you don't. You can use a
RIGHT JOIN instead, if there exist students without teacher.

If you have a real 1 to 1 relationship, omit the groupBy attribut and
the result element for property "sid". Otherwise use List<Student> in
class Teacher.

StudentDAOImpl
{
	public Student findStudent(Integer id)
	{
		return (Student)
getSqlMapClientTemplate().queryForObject("<NAMESPACE>.findStudent", id)	
	}
}

Somewhere in your business code you can write something like that:

Integer id = ...
Student student = this.studentDAO.findStudent(id);
if (student != null)
{
	Teacher teacher = student.getTeacher();
	if (teacher != null)
	{
		teacher.setStudent(student);
	}
}

Mime
View raw message