mybatis中表的关联
一、数据库中表的关联有三种形式
a)一对一
b)一对多(多对一)
c)多对多
二、mybatis实现多对一(两种方式)、这里我们用用户和部门进行举例实现(多个用户(员工)同属于一个部门、一个部门有多个用户(员工))
a)结果嵌套查询
dao接口:
List<User> selectAllUsers();
dao实现类:
@Override public List<User> selectAllUsers() { SqlSession sqlSession=null; List<User> userList = null; try { userList = MyBatisUtils.getSqlSesion("mybatis/mybatis.xml").selectList("edu.aeon.mybatis.entity.UserMapper.selectAllUsers"); } catch (IOException e) { e.printStackTrace(); } return userList; }
实体类和数据库的sql映射文件:(User.Mapper.xml)
<!-- ①多对一 :按结果嵌套--> <select id="selectAllUsers" resultMap="UserDepartment"> select u.*,d.* from user u,department d where u.did = d.did </select> <resultMap type="User" id="UserDepartment"> <id property="uid" column="uid"/> <result property="uname" column="uname"/> <result property="upw" column="upw"/> <association property="department" javaType="Department"> <id property="did" column="did"/> <result property="dname" column="dname"/> </association> </resultMap>
测试类:
public static void testSelectAllUsers(){ UserDao userDao =new UserDaoImpl(); List<User> userList = userDao.selectAllUsers(); for(User user:userList){ System.out.println(user); } }
b)按查询嵌套
dao及实现同上
mybatis核心配置文件:
<mappers> <!-- 引入实体类到数据库的sql映射文件 --> <mapper resource="edu/aeon/mybatis/entity/User.Mapper.xml"/> <mapper resource="edu/aeon/mybatis/entity/Deparment.Mapper.xml"/> </mappers>
实体类和数据库的sql映射文件:(User.Mapper.xml)
<!-- ②多对一 :按查询嵌套--> <select id="selectAllUsers" resultMap="UserDepartment"> select * from user </select> <resultMap type="User" id="UserDepartment"> <association property="department" column="did" javaType="Department" select="edu.aeon.mybatis.entity.DepartmentMapper.selectDepartmentById"></association> </resultMap>
实体类和数据库的sql映射文件:(Deparment.Mapper.xml)
<mapper namespace="edu.aeon.mybatis.entity.DepartmentMapper"> <select id="selectDepartmentById" parameterType="int" resultType="Department"> select * from department where did=#{did} </select> </mapper>
测试同上!