mybatis mapper接口开发dao层
本文将探讨使用 mapper接口,以及 pojo 包装类进行 dao 层基本开发
mybatis dao 层开发只写 mapper 接口
其中需要 开发的接口实现一些开发规范
1、 UserMapper.xml 这个配置文件中的namespace应该是 mapper 接口的地址
2、 UserMapper.java 中的方法名与UserMapper.xml 的 statementid 要保持一致
3、 第二点中的方法 输入参数 与 返回值均要 跟 UserMapper.xml 中配置好的 parametertype , resulttype 保持一致
满足这样的规范, mybatis 通过读取xxx_mapper.xml 这样的 配置文件即可通过反射创建 该 mapper 接口的 实现类。
由于涉及到的查询结果列已经不再是单纯的 pojo 对象的属性能够包含的
所以本示例代码中的对于简单java对象进行一次包装
UserOrderWrapperFirst
为啥叫这个名呢,因为我认为这个类不是终点,我可能后面还会写一个UserOrderWrapper包装类,所以暂且先叫First好了
同样老套路先上项目结构图
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias type="com.ghc.pojo.User" alias="user"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="Mede645"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/UserMapper.xml"/> </mappers> </configuration>
<?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="com.ghc.dao.UserDao"> <select id="findUserById" parameterType="int" resultType="user"> SELECT * FROM user WHERE id = #{id} </select> <resultMap id="findUserOrderMapper" type="com.ghc.pojo.UserOrderWrapperFirst"> <!--因为继承自Order类,所以这些都可以看做是Order这个对象的基本属性--> <id column="id" property="id"/> <result column="user_id" property="user_id"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <!--配置映射关联的用户信息--> <!-- association: 用于映射关联查询单个对象的信息--> <!----> <association property="user" javaType="com.ghc.pojo.User"> <!--此处本可以写成user 但是为了突出就不用别名了 下面都是封装 wrapper 包装类的user对象到一个User的bean中--> <id column="user_id" property="id"/> <!--唯一标识用户的列就是主外键列 user_id 是 Order 的基本属性--> <result column="username" property="userName"/> <result column="birthday" property="birthday"/> <result column="sex" property="sex"/> <result column="address" property="address"/> </association> </resultMap> <select id="findUserOrder" resultMap="findUserOrderMapper"> select o.*,u.* from user u join orders o on u.id = o.user_id </select> <!-- select o.*,u.* from user u join orders o on u.id = o.user_id --> </mapper>
log4j.rootLogger=DEBUG,A1
log4j.logger.org.springframework=debug
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ghc</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>mybatis Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> </dependencies> <build> <finalName>mybatis</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
package com.ghc.pojo; import java.util.Date; public class User { private int id; private String userName; private Date birthday; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
package com.ghc.pojo; import java.util.Date; public class Orders { private int id; private int user_id; private String number; private Date createtime; private String note; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
package com.ghc.pojo; import java.util.Date; public class UserOrderWrapperFirst extends Orders{ private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
package com.ghc.dao; import com.ghc.pojo.User; import com.ghc.pojo.UserOrderWrapperFirst; import java.util.List; public interface UserDao { User findUserById(int id); List<UserOrderWrapperFirst> findUserOrder(); }
import com.ghc.dao.UserDao; import com.ghc.pojo.UserOrderWrapperFirst; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import com.ghc.pojo.User; public class UserDaoTest { private SqlSessionFactory sqlSessionFactory; @Before public void injectSqlSessionFactory() throws IOException { sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config/SqlMappingConfig.xml")); } @Test public void testFindUserById(){ UserDao userDao = sqlSessionFactory.openSession().getMapper(UserDao.class); User user = userDao.findUserById(1); System.out.println(user.getUserName()); List<UserOrderWrapperFirst> userOrderWrapperFirstList = userDao.findUserOrder(); for(UserOrderWrapperFirst userOrder:userOrderWrapperFirstList){ String userName = userOrder.getUser().getUserName(); int orderId = userOrder.getId(); System.out.println(userName+" <-----> "+String.valueOf(orderId)); } } }
效果图:
总结一波:
对于普通 java 对象 也就是 pojo 不能满足 mapper 映射要求的,需要扩展类集成基本的简单 java 对象,例如本例中,创建新类继承Order类,并在其内部增加一个 User 对象
用来接收 关联查询后的 用户信息,如图:
这一次算是把 pojo包装对象与 resultmap 区别于 (resultType 这个需要列名与属性名保持一致) , 做了一次demo
动态 sql 的我会另开一篇,留存配置