先写一个实体,用来做各种操作
实现序列化接口,便于对象转为二进制进行传输(序列化反序列化)
import java.io.Serializable; import java.util.List; public class QueryVo implements Serializable { private static final long serialVersionUID = 1L; // private User user; List<Integer> idsList; Integer[] ids; public List<Integer> getIdsList() { return idsList; } public void setIdsList(List<Integer> idsList) { this.idsList = idsList; } public Integer[] getIds() { return ids; } public void setIds(Integer[] ids) { this.ids = ids; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
动态SQL
UserMapper.xml中的<if>标签、1=1用法、<where>标签(作用:去掉第一个and)
SQL片段(公共的片段,复用)
<sql id="selector"> select * from user </sql> <!-- 根据性别和名字查询用户 where 可以去掉第一个前ANd --> <select id="selectUserBySexAndUsername" parameterType="User" resultType="User"> <include refid="selector"/> <where> <if test="sex != null and sex != ''"> and sex = #{sex} </if> <if test="username != null and username != ''"> and username = #{username} </if> </where> </select>
foreach(你的sql中某个参数输入的条件是一个数组)
<!-- 多个ID (1,2,3) collection="list/array/vo" list对应List<Integer>参数 array对应Integer[]参数 --> <select id="selectUserByIds" parameterType="QueryVo" resultType="User"> <include refid="selector"/> <where> <foreach collection="list" item="id" separator="," open="id in (" close=")"> #{id} </foreach> </where> </select>
关联查询(连接查询)
实体Orders
public class Orders implements Serializable{ private static final long serialVersionUID = 1L; private Integer id; private Integer userId; private String number; private Date createtime; private String note; //附加对象 用户对象 private User user;
一对一
<!-- //一对一关联 查询 以订单为中心 关联用户 public List<Orders> selectOrders(); --> <resultMap type="Orders" id="order"> <result column="id" property="id"/> <result column="user_id" property="userId"/> <result column="number" property="number"/> <!-- 一对一 --> <association property="user" javaType="User"> <id column="user_id" property="id"/> <result column="username" property="username"/> </association> </resultMap> <select id="selectOrders" resultMap="order"> SELECT o.id, o.user_id, o.number, o.createtime, u.username FROM orders o left join user u on o.user_id = u.id </select>
实体User
public class User implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 //附加对象List private List<Orders> ordersList;
一对多
<!-- //一对多关联 public List<User> selectUserList(); --> <resultMap type="User" id="user"> <id column="user_id" property="id"/> <result column="username" property="username"/> <!-- 一对多 --> <collection property="ordersList" ofType="Orders"> <id column="id" property="id"/> <result column="number" property="number"/> </collection> </resultMap> <select id="selectUserList" resultMap="user"> SELECT o.id, o.user_id, o.number, o.createtime, u.username FROM user u left join orders o on o.user_id = u.id </select>
Mybatis与Spring整合
- SqlSessionFactory对象应该放到spring容器中作为单例存在。
- 传统dao的开发方式中,应该从spring容器中获得sqlsession对象。
- Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。
- 数据库的连接以及数据库连接池事务管理都交给spring容器来完成。
jar包
- spring的jar包
- Mybatis的jar包
- Spring+mybatis的整合包。
- Mysql的数据库驱动jar包。
- 数据库连接池的jar包。

aopalliance-1.0.jar asm-3.3.1.jar aspectjweaver-1.6.11.jar cglib-2.2.2.jar commons-dbcp-1.2.2.jar commons-logging-1.1.1.jar commons-pool-1.3.jar javassist-3.17.1-GA.jar jstl-1.2.jar junit-4.9.jar log4j-1.2.17.jar log4j-api-2.0-rc1.jar log4j-core-2.0-rc1.jar mybatis-3.2.7.jar mybatis-spring-1.2.2.jar mysql-connector-java-5.1.7-bin.jar slf4j-api-1.7.5.jar slf4j-log4j12-1.7.5.jar spring-aop-4.1.3.RELEASE.jar spring-aspects-4.1.3.RELEASE.jar spring-beans-4.1.3.RELEASE.jar spring-context-4.1.3.RELEASE.jar spring-context-support-4.1.3.RELEASE.jar spring-core-4.1.3.RELEASE.jar spring-expression-4.1.3.RELEASE.jar spring-jdbc-4.1.3.RELEASE.jar spring-jms-4.1.3.RELEASE.jar spring-messaging-4.1.3.RELEASE.jar spring-tx-4.1.3.RELEASE.jar spring-web-4.1.3.RELEASE.jar spring-webmvc-4.1.3.RELEASE.jar
配置文件
sqlMapConfig.xml
<?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> <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 --> <package name="com.itheima.mybatis.pojo" /> </typeAliases> <mappers> <package name="com.itheima.mybatis.mapper"/> </mappers> </configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <context:property-placeholder location="classpath:db.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="5" /> </bean> <!-- Mybatis的工厂 放到spring容器--> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 核心配置文件的位置 --> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> </bean> <!-- Dao原始Dao 放到spring容器--> <bean id="userDao" class="com.itheima.mybatis.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/> </bean> <!-- Mapper动态代理开发 放到spring容器--> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/> <property name="mapperInterface" value="com.itheima.mybatis.mapper.UserMapper"/> </bean> <!-- Mapper动态代理开发 扫描 放到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 基本包 --> <property name="basePackage" value="com.itheima.mybatis.mapper"/> </bean> </beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8 jdbc.username=root jdbc.password=root
log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
原始dao开发
import org.mybatis.spring.support.SqlSessionDaoSupport; /** * 原始Dao开发 * @author lx * */ public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ //声明工厂 public void insertUser(){ // this.getSqlSession().insert(arg0, arg1) } }
spring容器接手dao(条件是给它一个sqlSessionFactory)
<!-- Dao原始Dao --> <bean id="userDao" class="com.itheima.mybatis.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/> </bean>
spring容器管理mapper(只要你给它两个东西:sqlSessionFactory和mapperInterface)
<!-- Mapper动态代理开发 --> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/> <property name="mapperInterface" value="com.itheima.mybatis.mapper.UserMapper"/> </bean>
给spring的东西其实就是红色(为了说明问题)
@Test public void testMapper() throws Exception { //加载核心配置文件 String resource = "sqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); //创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //SqlSEssion帮我生成一个实现类 (给接口) UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserById(10); System.out.println(user); }
测试
指定mapper的位置
<mappers> <package name="com.itheima.mybatis.mapper"/> </mappers>
@Test public void testMapper() throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper mapper = ac.getBean(UserMapper.class); // UserMapper mapper = (UserMapper) ac.getBean("userMapper"); User user = mapper.findUserById(10); System.out.println(user); }
动态代理开发增强版
<!-- Mapper动态代理开发 扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 基本包 --> <property name="basePackage" value="com.itheima.mybatis.mapper"/> </bean>
逆向工程
(这个目前在idea的springboot开发中很EZ,这些工具类,一个一个积累)
完了这个测试类有点意思
@Test public void testMapper() throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = ac.getBean(UserMapper.class); UserExample example = new UserExample(); String username = "明"; example.createCriteria().andSexEqualTo("1").andUsernameLike("%" + username + "%"); example.setOrderByClause("id desc"); int countByExample = userMapper.countByExample(example); System.out.println(countByExample); User user = userMapper.selectByPrimaryKey(10); System.out.println(user); List<User> users = userMapper.selectByExample(example); for (User user2 : users) { System.out.println(user2.getId()); } }
有空再看看gacl的mybatis篇