pom.xml导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 数据库连接池使用druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
在spirng的配置文件当中集成mybatis,spring将mybatis的配置文件抽离成一个一个bean标签,但是还是要配置映射文件,注释上有标注
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/user_test?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--使用注解配置事务-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.entor"></context:component-scan>
<!-- 配置mybatis会话工厂 mybatisConfiguration.xml -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<!-- 加载orm映射文件mappers -> mapper -->
<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
<property name="typeAliasesPackage" value="com.entor.entity"></property>
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<property name="mapUnderscoreToCamelCase" value="true"></property>
<property name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"></property>
<property name="cacheEnabled" value="true"></property>
</bean>
</property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
</bean>
<!-- 自动扫描指定包下的接口,为接口创建实现类对象 session.getMapper(xxx.class)-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定接口包名-->
<property name="basePackage" value="com.entor.mappers"></property>
<!-- 配置会话工厂,系统中存在单个工厂不用配置-->
<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
</bean>
<!-- mybatis配置类-->
</beans>
mybatis的映射类
package com.entor.mappers;
import com.entor.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
*@describe 打开了二级缓存的小开关,使用二级缓存策略
**/
@CacheNamespace
public interface UserMapper {
/**
*@describe 插入单条记录,返回新增的主键
**/
// @Insert("insert into emp(id,name,sex,phone,email,entry_date,create_time,password)" +
// "values(#{name},#{sex},#{phone},#{email},#{entry_date},#{create_time},#{password})")
public abstract int add(User user);
/**
*@describe 向数据库中插入多条记录
* @param
* @return
**/
public abstract int addMore(List<User> list);
/**
*@describe 更新数据库中的记录
**/
// @Update("update empset name=#{name},sex=#{sex},phone=#{phone},email=#{email},entry_date=#{entry_date},create_time=#{create_time},password=#{password}" +
// "where id = #{id}")
public abstract int update(User user);
/**
*@describe 根据id删除单条记录
**/
@Delete("delete from emp where id = #{id}")
public abstract int deleteById(int id);
/**
*@describe 根据ids删除多条记录
**/
@Delete("delete from emp where id in (${ids})")
public abstract int deleteByIds(String ids);
/**
*@describe 根据id查询用户
**/
@Select("select id,name,sex,phone,email,entry_date,create_time,password from emp where id = #{id}")
public abstract User queryById(int id);
/**
*@describe 分页查询
**/
@Select("select id,name,sex,phone,email,entry_date," +
"create_time,password from emp limit #{pageNum},#{pageSize}")
public abstract List<User> queryByPage
(@Param("pageNum") int pageNo, @Param("pageSize") int pageSize);
/**
*@describe 方法上有多个参数,为了区分不同参数需要在参数前面加上@Param的注解来指定参数名称,单个参数不需要
**/
/**
*@describe 用户登录
*
* @return User
**/
public abstract User login(String name,String password);
/**
*@describe 查询数据库中的总记录数
**/
@Select("select count(id) from emp")
public abstract int getCount();
@Select("select * from emp")
public abstract List<User> queryAll();
//
// @Select("select * from emp where name like concat('%',#{name},'%')" +
// " and sex like concat('%',#{sex},'%') order by name")
public abstract List<User> queryByParam(User user);
}
mybatis映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.entor.mappers.UserMapper">
<sql id="common">
id,name,sex,phone,email,entry_date,create_time,password
</sql>
<sql id="common2">
name,sex,phone,email,entry_date,create_time,password
</sql>
<insert id="add">
insert into emp (
<if test="name!=null and name !=''">
name,
</if>
<if test="sex!=null and sex !=''">
sex,
</if>
<if test="phone!=null and phone !=''">
phone,
</if>
<if test="email!=null and email !=''">
email,
</if>
<if test="entry_date!=null ">
entry_date,
</if>
<if test="create_time!=null">
create_time,
</if>
<if test="password!=null and password !=''">
password
</if>
)
values (
<if test="name!=null and name !=''">
#{name},
</if>
<if test="sex!=null and sex !=''">
#{sex},
</if>
<if test="phone!=null and phone !=''">
#{phone},
</if>
<if test="email!=null and email !=''">
#{email},
</if>
<if test="entry_date!=null">
#{entry_date},
</if>
<if test="create_time!=null ">
#{create_time},
</if>
<if test="password!=null and password !=''">
#{password}
</if>
)
</insert>
<insert id="addMore" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into emp(<include refid="common2"/>)values
<foreach collection="list" separator="," item="user">
(#{user.name},
#{user.sex},
#{user.phone},
#{user.email},
#{user.entry_date},
#{user.create_time},
#{user.password})
</foreach>
</insert>
<update id="update">
update emp
<set>
<if test="name!=null and name !=''">
name=#{name},
</if>
<if test="sex!=null and sex !=''">
sex=#{sex},
</if>
<if test="phone!=null and phone !=''">
phone=#{phone},
</if>
<if test="email!=null and email !=''">
email=#{email},
</if>
<if test="entry_date!=null">
entry_date=#{entry_date},
</if>
<if test="create_time!=null ">
create_time=#{create_time},
</if>
<if test="password!=null and password !=''">
password=#{password}
</if>
</set>
where id = #{id}
</update>
<!--使用${}拼接参数有sql注入的风险-->
<!--mysql自带拼接参数concat,可以防止sql注入(推荐使用)-->
<!-- 在调用的时候再参数两侧加%号 -->
<select id="queryByParam" resultType="User">
select <include refid="common"/> from emp
<where>
<if test="name!=null and name!=''">
name like concat('%' ,#{name},'%')
</if>
<if test="sex!=null">
and sex = #{sex}
</if>
<if test="phone!=null and phone!=''">
and phone like concat('%' ,#{phone},'%')
</if>
</where>
</select>
</mapper>
将简单的sql语句放在类当中,把复杂的sql语句放在xml当中,这是一般的开发模式,如果有实现方法重复的问题就会报某某某方法已经存在的错误
开始进行测试,可以通过bean直接获取映射类了
ClassPathXmlApplicationContext cal = new ClassPathXmlApplicationContext("/applicationContext.xml");
UserMapper bean = cal.getBean(UserMapper.class);
注解开发
package com.entor.entor2.entor.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@EnableTransactionManagement
@Configuration
@MapperScan(basePackages = "com.entor.mappers")
@ComponentScan(basePackages = "com.entor")
@PropertySource(value = "classpath:db.properties")
public class SpringMybatisConfig {
@Value("${et.driver}")
private String driver;
@Value("${et.url}")
private String url;
@Value("${et.username}")
private String username;
@Value("${et.password}")
private String password;
@Value("${et.mapperResource}")
private String mappers;
@Value("${et.aliasesPackage}")
private String aliases;
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
@Bean
public TransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResource(mappers));
sqlSessionFactoryBean.setTypeAliasesPackage(aliases);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setLogImpl(StdOutImpl.class);
configuration.setCacheEnabled(true);
//使用plus
sqlSessionFactoryBean.setConfiguration(configuration);
sqlSessionFactoryBean.setPlugins(new PageInterceptor());
return sqlSessionFactoryBean.getObject();
}
}