Mybatis3:

<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>


</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
</plugins>
</build>

log4j.properties

#log4j.rootCategory=ERROR, CONSOLE,LOGFILE
log4j.rootCategory=ERROR, CONSOLE
log4j.logger.com.fly.mapper=DEBUG

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %p %m %n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=C:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%C %m %L %n

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

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>
<!-- 使用resource属性加载外部配置文件 -->
<properties resource="config/db.properties"/>

<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<!-- 单个别名定义 -->
<!--<typeAlias alias="user" type="com.fly.pojo.User"/>-->
<!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感)-->
<package name="com.fly.pojo"/>
</typeAliases>
<!--environments(环境集合属性对象)-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC"/>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>

<!--加载映射文件-->
<mappers>
<!--<mapper resource="com/fly/mapper/UserMapper.xml"/>-->
<!--要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中-->
<mapper class="com.fly.mapper.UserMapper"/>
</mappers>
</configuration>

User:

public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址

//用作一对多
private List<Order> orders;

Order:

public class Order {
// 订单id
private int id;
// 用户id
private Integer userId;
// 订单号
private String number;
// 订单创建时间
private Date createtime;
// 备注
private String note;

//用作一对一
private User user;

QueryVo:

public class QueryVo {
private List<Integer> ids;

OrderUser:

public class OrderUser extends Order{
private String username;
private String address;

UserMapper:

public interface UserMapper {
User queryUserById(int id);
List<User> queryUserByName(String name);
int saveUser(User user);
List<User> queryUserByWhere(User user);
List<User> queryUserByIds(QueryVo queryVo);
//一对一关联
List<OrderUser> queryOrderUser();
List<Order> queryOrderUser1();
//一对多
List<User>queryUserOrder();
}

UserMapper.xml:

<?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.fly.mapper.UserMapper">
<!-- id:statement的id 或者叫做sql的id-->
<!-- parameterType:声明输入参数的类型 -->
<!-- 如果返回多个结果,mybatis会自动把返回的结果放在list容器中 -->
<!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
<!-- #{}:输入参数的占位符,相当于jdbc的? -->
<select id="queryUserById" parameterType="int" resultType="user">
select *
from user
where id = #{id}
</select>
<!-- 如果传入的参数是简单数据类型,${}里面必须写value -->
<select id="queryUserByName" parameterType="string" resultType="user">
# select * from user where username like '%${value}%'
select *
from user
where username like #{name}
</select>
<!--
#{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换。
#{}可以有效防止sql注入。
#{}可以接收简单类型值或pojo属性值。
如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

${}表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换,
${}可以接收简单类型值或pojo属性值,
如果parameterType传输单个简单类型值,${}括号中只能是value
-->
<insert id="saveUser" parameterType="user">
/* 标签实现主键返回*/
/*在执行insert语句之后执行查询id的sql*/
/*resultType:设置返回的id的类型*/
<selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="int">
/*mysql的函数,返回auto_increment自增列新记录id值*/
select last_insert_id()
</selectKey>
insert into user(username, birthday, sex, address) VALUES (#{username},#{birthday},#{sex},#{address})
</insert>

<sql id="userFields">
id,username,birthday,sex,address
</sql>
<select id="queryUserByWhere" parameterType="user" resultType="user">
select <include refid="userFields"/> from user
<where>
<if test="sex!=null">
and sex=#{sex}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</where>
</select>
<!--方式一-->
<select id="queryUserByIds" parameterType="queryVo" resultType="user">
select <include refid="userFields"/> from user
<where>
<!-- foreach标签,进行遍历 -->
<!-- collection:遍历的集合,这里是QueryVo的ids属性 -->
<!-- item:遍历的项目,和后面的#{}里面要一致 -->
<!-- open:在前面添加的sql片段 -->
<!-- close:在结尾处添加的sql片段 -->
<!-- separator:指定遍历的元素之间使用的分隔符 -->
<foreach collection="ids" item="i" open="id in (" close=")" separator=",">
#{i}
</foreach>
</where>
</select>
<!-- 查询订单,同时包含用户数据 -->
<select id="queryOrderUser" resultType="orderUser">
select
o.id,o.user_id userId,o.number,o.createtime,
u.username,u.address
from orders o left join user u on o.user_id = u.id
</select>

<!--一对一-->

<resultMap id="orderUserResultMap" type="order">
<id property="id" column="id"/>
<!--<result property="userId" column="user_id"/>-->
<result property="userId" column="userId"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<!-- association :配置一对一属性 -->
<!-- property:order里面的User属性名 -->
<!-- javaType:属性类型 -->
<association property="user" javaType="user">
<!-- id:声明主键,表示user_id是关联查询对象的唯一标识-->
<!--<id property="id" column="user_id"/>-->
<id property="id" column="userId"/>
<result property="username" column="username"/>
<result property="address" column="address" />
</association>
</resultMap>
<select id="queryOrderUser1" resultMap="orderUserResultMap">
select
o.id,o.user_id userId,o.number,o.createtime,
u.username,u.address
from orders o left join user u on o.user_id = u.id
</select>
<!--一对一
其他方式
-->
<select id="selById" resultType="user" parameterType="int">
select * from user where id=#{id}
</select>
<resultMap id="orderUserResultMap2" type="order">
<!--列名和属性名相同可以不配置-->
<result property="userId" column="user_id"/>
<!--select:通过哪个查询查询出这个对象的信息
column: 把当前表的哪个列的值做为参数传递给另一个查询-->
<association property="user" javaType="user" column="user_id" select="com.fly.mapper.UserMapper.selById"/>
</resultMap>
<select id="queryOrderUser2" resultMap="orderUserResultMap2">
select * from orders
</select>
<!--
一对一其他方式
使用 Auto Mapping 结合别名实现
-->
<select id="queryOrderUser3" resultType="order">
select
o.id,o.user_id userId,o.number,o.createtime,
u.id `user.id`,u.username `user.username`,u.address `user.address`
from orders o left join user u on o.user_id = u.id
</select>

<!--一对多-->
<resultMap id="userOrderResultMap" type="user">
<id property="id" column="id"/>
<result property="username" column="username" />
<result property="birthday" column="birthday" />
<result property="sex" column="sex" />
<result property="address" column="address" />
<!-- 配置一对多的关系 -->
<collection property="orders" javaType="list" ofType="order">
<id property="id" column="oid"/>
<result property="userId" column="userId"/>
<!--<result property="userId" column="user_id"/>
column 对应sql语句中的字段,注意是否重命名
-->
<result property="number" column="number"/>
<result property="createtime" column="createtime" />
</collection>
</resultMap>
<select id="queryUserOrder" resultMap="userOrderResultMap">
select
u.id,u.username,u.birthday,u.sex,u.address,
o.id oid,o.user_id userId,o.number, o.createtime
from user u left join orders o on u.id = o.user_id
</select>
<!--一对多
其他
-->
<select id="selOrderById" parameterType="int" resultType="order">
select id, user_id userId, number, createtime, note from orders where user_Id=#{userId}
</select>
<resultMap id="userOrderResultMap2" type="user">
<id property="id" column="id"/>
<result property="username" column="username" />
<result property="birthday" column="birthday" />
<result property="sex" column="sex" />
<result property="address" column="address" />
<collection property="orders" javaType="list" select="com.fly.mapper.UserMapper.selOrderById" ofType="order" column="id"/>
</resultMap>
<select id="queryUserOrder2" resultMap="userOrderResultMap2">
select * from user
</select>
</mapper>

MybatisTest:

public class MybatisTest {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void init() throws IOException {
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("config/SqlMapConfig.xml");
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}

@Test
public void test(){
SqlSession sqlSession = sqlSessionFactory.openSession();
Object user = sqlSession.selectOne("queryUserById", 1);
System.out.println(user);
sqlSession.close();
}
@Test
public void test1(){
SqlSession sqlSession = sqlSessionFactory.openSession();
// List<User> user = sqlSession.selectList("queryUserByName", "小");
List<User> user = sqlSession.selectList("queryUserByName", "%小%");
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}

@Test
public void test01(){
SqlSession sqlSession = sqlSessionFactory.openSession();
//参数二 parameter 参数三 mapKey
Map<Object, Object> map = sqlSession.selectMap("queryUserById", 16, "username");
System.out.println(map);//{张小明=User{id=16, username='张小明', sex='1', birthday=null, address='河南郑州'}}
sqlSession.close();
}


@Test
public void test11(){
SqlSession sqlSession = sqlSessionFactory.openSession();
// 从sqlSession中获取Mapper接口的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.queryUserByName("%小%");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}

@Test
public void test2(){
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("张飞");
user.setBirthday(new Date());
user.setSex("1");
user.setAddress("aa");
sqlSession.insert("saveUser", user);
System.out.println(user.getId());
sqlSession.commit();
sqlSession.close();
}
@Test
public void test3(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("小");
user.setSex("1");
List<User> users = mapper.queryUserByWhere(user);
for (User user1 : users) {
System.out.println(user1);
}
sqlSession.close();
}
@Test
public void testqueryUserByIds(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
QueryVo queryVo = new QueryVo();
List<Integer> ids = new ArrayList<>();
ids.add(24);
ids.add(25);
ids.add(26);
queryVo.setIds(ids);
List<User> list = mapper.queryUserByIds(queryVo);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}

/**
* 一对一关联查询
*/
@Test
public void testQueryOrderUser(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<OrderUser> list = mapper.queryOrderUser();
for (OrderUser orderUser : list) {
System.out.println(orderUser);
}
sqlSession.close();
}
@Test
public void testQueryOrderUser1(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<Order> list = mapper.queryOrderUser1();
for (Order order : list) {
System.out.println(order);
}
sqlSession.close();
}
@Test
public void testQueryUserOrder(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.queryUserOrder();
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
}

补充:多参数情况

UserMapper.xml

<!--多参数情况-->
<!-- #{}中使用 arg0,arg1
# select * from user where username like #{arg0} and sex=#{arg1}
param1,param2-->
<select id="selByUsernameAndSex" resultType="user">
select * from user where username like #{param1} and sex=#{param2}
</select>
<!--使用注解方式-->
<select id="selByUsernameAndSex1" resultType="user">
select * from user where username like #{username} and sex=#{sax}
</select>

UserMapper

//多参数
List<User> selByUsernameAndSex(String username,String sax);
List<User> selByUsernameAndSex1(@Param("username") String username,@Param("sax") String sax);

测试:

public class MybatisTest2 {
SqlSessionFactory sessionFactory = null;
@Before
public void init() throws IOException {
InputStream rs = Resources.getResourceAsStream("config/SqlMapConfig.xml");
sessionFactory = new SqlSessionFactoryBuilder().build(rs);
}

@Test
public void test1(){
SqlSession session = sessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
// List<User> list = mapper.selByUsernameAndSex("%小%", "1");
List<User> list = mapper.selByUsernameAndSex1("%小%", "1");
for (User user : list) {
System.out.println(user);
}
session.close();
}
}

补充:动态sql

<!--动态sql
bind: 给参数重新赋值
-->
<select id="selByUsernameAndSex2" resultType="user">
select * from user
<where>
<if test="username!=null and username!=''">
<bind name="username" value="'%'+username+'%'"/>
and username like #{username}
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex}
</if>
</where>
</select>
<!-- <choose> <when> <otherwise>
执行第一个不为null的when
只要有一个when成立,其它都不执行,若都不成立执行otherwise
没设置otherwise就不执行where
-->
<select id="selByUsernameAndSex3" resultType="user">
select * from user
<where>
<choose>
<when test="username!=null and username!=''">
<bind name="username" value="'%'+username+'%'"/>
and username like #{username}
</when>
<when test="sex!=null and sex!=''">
and sex=#{sex}
</when>
<otherwise>
and id=24
</otherwise>
</choose>
</where>
</select>
<update id="updateUser" parameterType="user">
update user
<set>
id=#{id},
<if test="username!=null and username!=''">
username=#{username},
</if>
<if test="birthday!=null">
birthday=#{birthday},
</if>
<if test="sex!=null and sex!=''">
sex=#{sex},
</if>
<if test="address!=null and address!=''">
address=#{address},
</if>
</set>
where id=#{id}
</update>
<!--trim
prefix 在前面添加内容
prefixOverrides 去掉前面内容
suffix 在后面添加内容
suffixOverrieds 去掉后面内容
执行顺序去掉内容后添加内容
-->
<update id="updateUser1" parameterType="user">
update user
<trim prefix="set" suffixOverrides=",">
id=#{id},
<if test="username!=null and username!=''">
username=#{username},
</if>
<if test="birthday!=null">
birthday=#{birthday},
</if>
<if test="sex!=null and sex!=''">
sex=#{sex},
</if>
<if test="address!=null and address!=''">
address=#{address},
</if>
</trim>
where id=#{id}
</update>

ThreadLocal的使用:

public class MyBatisUtil {
private static SqlSessionFactory factory;
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
static {
try {
InputStream rs = Resources.getResourceAsStream("config/SqlMapConfig.xml");
factory =new SqlSessionFactoryBuilder().build(rs);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取sqlSession
*/
public static SqlSession getSession(){
SqlSession sqlSession = threadLocal.get();
if (sqlSession==null){
threadLocal.set(factory.openSession());
}
return threadLocal.get();
}
/**
* 关闭sqlSession
*/
public static void closeSession(){
SqlSession sqlSession = threadLocal.get();
if (sqlSession!=null){
sqlSession.close();
}
threadLocal.set(null);
}
}

测试:

@Test
public void test3(){
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> list = mapper.selByUsernameAndSex3(null, null);
for (User user : list) {
System.out.println(user);
}
MyBatisUtil.closeSession();
}

补充:注解方式:

//一对一关联 注解方式
@Results(value = {
@Result(property = "userId",column = "user_id"),
@Result(property = "user",javaType = User.class,column = "user_id",one = @One(select = "com.fly.mapper.UserMapper.selById"))
})
@Select("select * from orders")
List<Order> queryOrderUser4();

//一对多 注解方式
@Results(value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "sex",column = "sex"),
@Result(property = "address",column = "address"),
@Result(property = "orders",column = "id",javaType = List.class,many = @Many(select = "com.fly.mapper.UserMapper.selOrderById"))
})
@Select("select * from user")
List<User> queryUserOrder3();

补充:执行流程

MyBatis 运行开始时需要先通过 Resources 加载全局配置文件.
然后需要实例化 SqlSessionFactoryBuilder 构建器.帮助 SqlSessionFactory 接口实现类 DefaultSqlSessionFactory
在实例化 DefaultSqlSessionFactory 之前需要先创建 XmlConfigBuilder 解析全局配置文件流,
并把解析结果存放在 Configuration 中.
之后把Configuratin 传递给 DefaultSqlSessionFactory.到此 SqlSessionFactory 工 厂创建成功
SqlSessionFactory 工厂创建 SqlSession. 每次创建 SqlSession 时,都需要由 TransactionFactory 创建 Transaction对象,
同时还需要创建 SqlSession 的执行器 Excutor,
最后实例化DefaultSqlSession,传递给 SqlSession 接口.
根据项目需求使用 SqlSession 接口中的 API 完成具体的事务操作.
如果事务执行失败,需要进行 rollback 回滚事务. 如果事务执行成功提交给数据库.关闭 SqlSession

Mybatis整合spring:

<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
</plugins>

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>
<package name="com.fly.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/fly/mapper/UserMapper.xml"/>
</mappers>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>
<!--加载配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置sqlSessionFactory-->

<!--
对象名和 ref=”id”id 名相同使用自动注入,可以不配置<property/>
autowire="byName" 通过名称自动注入.在 Spring 容器中找类的 Id
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置mybatis核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userDao" class="com.fly.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
<!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!--<!– 配置Mapper接口 –>-->
<!--<property name="mapperInterface" value="com.fly.mapper.UserMapper" />-->
<!--<!– 配置sqlSessionFactory –>-->
<!--<property name="sqlSessionFactory" ref="sqlSessionFactory" />-->
<!--</bean>-->
<!-- Mapper代理的方式开发方式二,扫描包方式配置代理
每个mapper代理对象的id就是类名,首字母小写
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper接口 -->
<property name="basePackage" value="com.fly.mapper" />

<!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
</bean>

<!--补充测试-->

<bean id="userService" class="com.fly.service.UserService">
<property name="userMapper" ref="userMapper"/>
</bean>
</beans>

UserDaoImpl

public class UserDaoImpl {
private SqlSessionFactory sqlSessionFactory;

public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public List<User> findByName(String username){
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> list = sqlSession.selectList("findByName", username);
return list;
// 不用提交,事务由spring进行管理
// 不要关闭sqlSession
}
}

UserMapper

public interface UserMapper {
List<User> findByName(String username);

@Select("select * from user where id = #{id}")
User findById(int id);
}

UserMapper.xml

<?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.fly.mapper.UserMapper">
<select id="findByName" resultType="user" parameterType="string">
select * from user where username like "%${value}%"
</select>
</mapper>

UserDaoTest

public class UserDaoTest {
private ApplicationContext context;
@Before
public void setUp() throws Exception {
this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}

@Test
public void testQueryUserById1() {
UserDaoImpl userDao = this.context.getBean(UserDaoImpl.class);
List<User> list = userDao.findByName("小");
for (User user : list) {
System.out.println(user);
}
}
// Mapper代理的方式
@Test
public void testQueryUserById() {
// 获取userDao
UserMapper mapper = this.context.getBean(UserMapper.class);
List<User> list = mapper.findByName("小");
for (User user : list) {
System.out.println(user);
}
}
// Mapper代理形式开发dao

}

UserService:

public class UserService {
private UserMapper userMapper;

public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User findById(int id){
return userMapper.findById(id);
}
}

补充测试:

//测试
@Test
public void test(){
//所有的bean
String[] names = context.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
UserService bean = context.getBean(UserService.class);
User user = bean.findById(1);
System.out.println(user);
}

优质内容筛选与推荐>>
1、js如何将字符串作为函数名调用函数
2、翻译 - 【Dojo Tutorials】Part 1 - Getting Started with Dojo Mobile
3、django.db.utils.OperationalError: (1050, "Table '表名' already exists)解决方法
4、httpd编译安装
5、python实现Telnet远程登陆到设备并执行命令


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号