sqlMapConfig.xml
别名
XXXMapper.xml
<select> <update> <delete>
applicationContext.xml
数据源
sqlSessionFactory
事务(暂且不配置)
mappers映射器
创建java工程
导jar包
mybatis包、mybatis扩展包、mybatis和spring的整合包、spring的包、jdbc驱动包、junit包
添加配置文件
log4j.properties
jdbc.properties
sqlMapConfig.xml
applicationContext.xml
接口+实现类(需要继承父类 SqlSessionDaoSurport与HibernateDaoSurport类似)+映射文件
新建项目mybatis-spring
导包
新建SourceFolder文件夹config
,导入配置文件
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
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://cloud.dmdream.cn:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=xxxx
sqlMapConfig.xml
<configuration>
<typeAliases>
<package name="cn.dmdream.mybatis.pojo" />
typeAliases>
<mappers>
<mapper resource="UserMapper.xml" />
mappers>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
settings>
configuration>
applicationContext.xml(完整)
<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:jdbc.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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
bean>
<bean id="userDao" class="cn.dmdream.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
beans>
接口类
UserDao.java
package cn.dmdream.mybatis.dao;
import cn.dmdream.mybatis.pojo.User;
public interface UserDao {
public User findById(int id);
public void insertUser(User user);
}
接口实现类 , 要继承SqlSessionDaoSupport
(类似HibernateDaoSurport)
UserDaoImpl.java
package cn.dmdream.mybatis.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import cn.dmdream.mybatis.dao.UserDao;
import cn.dmdream.mybatis.pojo.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findById(int id) {
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("findById", id);
//sqlSession.close(); //现在由spring容器管理
return user;
}
@Override
public void insertUser(User user) {
SqlSession sqlSession = this.getSqlSession();
sqlSession.insert("insertUser", user);
//sqlSession.commit();//现在由spring容器管理
//sqlSession.close();//现在由spring容器管理
}
}
接口映射文件
UserMapper.xml
<mapper namespace="cn.dmdream.mybatis.dao.UserDao">
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
select>
<insert id="insertUser" parameterType="cn.dmdream.mybatis.pojo.User">
<selectKey resultType="int" keyProperty="id" order="AFTER">
select LAST_INSERT_ID()
selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address});
insert>
mapper>
Spring配置文件中配置userDao并手动注入sqlSessionFactory
applicationContext.xml
<bean id="userDao" class="cn.dmdream.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
测试类
UserDaoTest
package cn.dmdream.mybatis.pojo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.dmdream.mybatis.dao.UserDao;
import cn.dmdream.mybatis.dao.impl.UserDaoImpl;
public class UserDaoTest {
public static void main(String[] args) {
// 1、加载spring容器|初始化容器
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 2、从容器中获取对象
// app.getBean("userDao");
UserDao userDao = app.getBean(UserDao.class);
User user = userDao.findById(30);
System.out.println(user);
}
}
接口+映射文件 代理对象的产生交给spring容器
新建UserMapper.java
和UserMapper.xml
注意五个规范
UserMapper.java
package cn.dmdream.mybatis.mapper;
import cn.dmdream.mybatis.pojo.User;
public interface UserMapper {
public User findById(int id);
}
UserMapper.xml
<mapper namespace="cn.dmdream.mybatis.mapper.UserMapper">
<select id="findById" parameterType="int" resultType="user" >
select * from user where id = #{id}
select>
mapper>
配置mapper代理对象
产生代理对象的方式一:使用MapperFactoryBean
生成代理对象交给Spring管理(几乎不用)
PS:只能为一个接口配置
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.dmdream.mybatis.mapper.UserMapper">property>
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
产生代理对象的方式二:使用 MapperScannerConfigurer
为包下的所有接口配置代理对象(建议使用)
mapper接口和映射文件在同一个目录
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.dmdream.mybatis.mapper">property>
bean>
mapper接口和映射文件不在在同一个目录
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:cn/itcast/mybatis/mapper/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.dmdream.mybatis.mapper">property>
bean>
可以删除mybatis的主配置文件了
将mybatis主配置文件中的连接池、别名、驼峰等设置交给Spring
<bean id="settings" class="org.apache.ibatis.session.Configuration">
<property name="mapUnderscoreToCamelCase" value="true">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="cn.dmdream.mybatis.pojo">property>
<property name="configuration" ref="settings">property>
bean>
测试类
UserMapperTest.java
public class UserMapperTest {
public static void main(String[] args) {
// 1、加载spring容器|初始化容器
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 2、从容器中获取对象
// app.getBean("userDao");
UserMapper mapper = app.getBean(UserMapper.class);
User user = mapper.findById(30);
System.out.println(user);
}
}
SpringMybatisDemo
若自己导包
News.java
package com.zjweu.entity;
public class News {//自己生成GetSetToStringConstruct
private Integer id;
private String title;
private String author;
private String content;
private String pubdate;
private String keyword;
}
NewsMapper.java
package com.zjweu.mapper;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.zjweu.entity.News;
@Repository
public interface NewsMapper {
public List<News> findAll();
}
NewsService.java
package com.zjweu.service;
import java.util.List;
import com.zjweu.entity.News;
public interface NewsService {
public List<News> findAll();
}
NewsServiceImpl.java
package com.zjweu.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zjweu.entity.News;
import com.zjweu.mapper.NewsMapper;
import com.zjweu.service.NewsService;
@Service
public class NewsServiceImpl implements NewsService {
@Autowired
private NewsMapper newsMapper;
public List<News> findAll() {
return newsMapper.findAll();
}
}
NewsMapper.xml
<mapper namespace="com.zjweu.mapper.NewsMapper">
<select id="findAll" resultType="news">
select * from tab_news
select>
mapper>
扩展阅读:mybatis 整合spring之mapperLocations配置的问题
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<context:annotation-config>context:annotation-config>
<context:component-scan base-package="com.zjweu">context:component-scan>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.drivername}">property>
<property name="url" value="${jdbc.url}">property>
<property name="username" value="${jdbc.username}">property>
<property name="password" value="${jdbc.password}">property>
<property name="maxActive" value="100">property>
<property name="maxIdle" value="20">property>
bean>
<bean id="settings" class="org.apache.ibatis.session.Configuration">
<property name="mapUnderscoreToCamelCase" value="true">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="mapperLocations" value="classpath:com/zjweu/mapper/*.xml">property>
<property name="typeAliasesPackage" value="com.zjweu.entity">property>
<property name="configuration" ref="settings">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zjweu.mapper">property>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
db.properties
jdbc.drivername=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://cloud.dmdream.cn:3306/zjweu?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
jdbc.username=root
jdbc.password=xxxx
@Service
@Transactional//开启事务
public class NewsServiceImpl implements NewsService{...}
@Repository
public interface NewsMapper{...}
TestNewsService.java
package com.zjweu.service;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.zjweu.entity.News;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class TestNewsService {
// @Test
// public void testFindAll(){
// ClassPathXmlApplicationContext context = new
// ClassPathXmlApplicationContext("applicationContext.xml");
// NewsService newsService = (NewsService)
// context.getBean("newsServiceImpl");
// List list = newsService.findAll();
// list.forEach(System.out::println);
// }
//使用springJunit4测试
@Autowired
private NewsService newsService;
@Test
public void testFindAll() {
List<News> list = newsService.findAll();
list.forEach(System.out::println);
}
}