一、创建数据库
二、建项目、建包、引入pom.xml、工具类
三、实体类层
四、接口
public interface PhoneMapper { public List<Phone> findAll(Phone phone); }
五、映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.kgc.mapper.PhoneMapper"> <select id="findAll" resultMap="findAll1"> select p.*,c.cname,pro.pname,con.conname from t_phone p,t_core c,t_producer pro,t_container con where p.id=c.pid and c.proid=pro.pid and p.id=con.pid </select> <resultMap id="findAll1" type="cn.kgc.entity.Phone"> <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="type" column="type"></result> <collection property="corelist" ofType="cn.kgc.entity.Core" resultMap="coreAAA"> <!--<id property="cId" column="cid"></id>--> <!--<result property="cName" column="cname"></result>--> </collection> <collection property="containerlist" ofType="cn.kgc.entity.Container"> <id property="conId" column="conid"></id> <result property="conName" column="conname"></result> </collection> </resultMap> <resultMap id="coreAAA" type="cn.kgc.entity.Core"> <id property="cId" column="cid"></id> <result property="cName" column="cname"></result> <association property="producer" javaType="cn.kgc.entity.Producer"> <id property="pId" column="pid"></id> <result property="pName" column="pname"></result> </association> </resultMap> </mapper>
六、主配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <properties resource="jdbc.properties"></properties> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/kgc/mapper/PhoneMapper.xml"/> </mappers> </configuration>
七、测试类
public class PhoneTest { @Test public void findListA(){ SqlSession sqlSession = StudentUtil.getSqlSession(); Phone phone = new Phone(); List<Phone> list = sqlSession.getMapper(PhoneMapper.class).findAll(phone); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i).getId()+"\t"); System.out.print(list.get(i).getName()+"\t"); System.out.print(list.get(i).getType()+"\t"); for(Core c : list.get(i).getCorelist()){ System.out.print(c.getcName()+"\t"); System.out.print(c.getProducer().getpName()+"\t"); } for(Container cc : list.get(i).getContainerlist()){ System.out.print(cc.getConName()+"\t"); } System.out.println(); } sqlSession.commit(); } }
八、结果