MyBatis与Spring的整合的入门案例
直接使用MyBatis框架的SqlSession访问数据库并不简便. Mybatis框架的重点是SQL映射文件.
pom.xml
<dependencies>
<!--Spring相关jar包-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- Mybatis相关jar包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<!-- <scope>test</scope>-->
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- spring-mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
package cn.lacknb.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
@Repository
public class User {
private Integer id;
@Value("王二")
private String username;
@Value("89898998")
private String password;
@Value("弦歌大道")
private String address;
public User(String username, String password, String address) {
this.username = username;
this.password = password;
this.address = address;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", address='" + address + '\'' +
'}';
}
}
package cn.lacknb.dao;
import cn.lacknb.beans.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserDao {
@Insert("insert into user(username, password, address) values(#{username}, #{password}, #{address})")
int addUser(User user);
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") Integer id);
@Update("update user set username=#{username}, password=#{password}, address=#{address} where id = #{id}")
int updateUser(User user);
@Select("select * from user where id = #{id}")
User find(@Param("id") Integer id);
@Select("select * from user")
List<User> findAll();
}
package cn.lacknb.service;
import cn.lacknb.beans.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
public interface UserService {
int addUser(User user);
int deleteUser(Integer id);
int updateUser(User user);
User find(Integer id);
List<User> findAll();
}
package cn.lacknb.service;
import cn.lacknb.beans.User;
import cn.lacknb.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public int addUser(User user) {
return userDao.addUser(user);
}
public int deleteUser(Integer id) {
return userDao.deleteUser(id);
}
public int updateUser(User user) {
return userDao.updateUser(user);
}
public User find(Integer id) {
return userDao.find(id);
}
public List<User> findAll() {
return userDao.findAll();
}
}
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" xmlns:tx="http://www.springframework.org/schema/tx"
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 http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 需要扫描的包(包括子包), 使注解生效-->
<context:component-scan base-package="cn.lacknb"/>
<!-- 读取properties文件-->
<!-- <context:property-placeholder location="xml/jdbc.properties"/>-->
<!-- 另一种读取多个properties文件|-->
<bean id="jdbcProperty" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/xml/jdbc.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源-->
<!-- 配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 添加事务支持-->
<!-- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
<!-- <property name="dataSource" ref="dataSource"/>-->
<!-- </bean>-->
<!-- <!– 开启事务注解–>-->
<!-- <tx:annotation-driven transaction-manager="txManager"/>-->
<!-- 配置mybatis工厂, 同时指定数据源, 并与mybatis完美结合-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- configlocation的属性值为mybatis的核心配置文件-->
<property name="configLocation" value="classpath:xml/mybatis-config.xml"/>
</bean>
<!-- Mapper代理开发,使用Spring自动扫描mybatis的接口并装配-->
<!--spring指定包中所有被@Mapper注解标注的接口自动装配为mybatis的映射接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- mybatis-Spring组件的扫描器-->
<property name="basePackage" value="cn.lacknb"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入外部配置文件 加入变量propertis-->
<properties resource="xml/jdbc.properties"/>
<settings>
<!-- 开启mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 任何方法的调用都会加载该对象的所有属性,否则每个属性都会按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 默认为true-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 配置别名-->
<typeAliases>
<package name="cn.lacknb.beans"/>
</typeAliases>
<!-- 起别名-->
<!-- <typeAliases>-->
<!-- <typeAlias type="MyUser" alias="beans"/>-->
<!-- </typeAliases>-->
<!-- 配置环境-->
<!-- <environments default="development">-->
<!-- <!– 配置mysql的环境, 和default保持一致–>-->
<!-- <environment id="development">-->
<!-- <!– 配置事务的类型 JDBC –>-->
<!-- <transactionManager type="JDBC"/>-->
<!-- <!– 配置数据源(连接池)–>-->
<!-- <dataSource type="POOLED">-->
<!-- <property name="driver" value="${jdbc.driver}"/>-->
<!-- <property name="url" value="${jdbc.url}"/>-->
<!-- <property name="password" value="${jdbc.password}"/>-->
<!-- <property name="username" value="${jdbc.username}"/>-->
<!-- </dataSource>-->
<!-- </environment>-->
<!-- </environments>-->
<!-- 指定带有注解的dao接口所在的位置-->
<mappers>
<package name="cn.lacknb.dao"/>
</mappers>
</configuration>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///jdbc_template?useSSL=false
jdbc.username=root
jdbc.password=123456
#log4j.rootLogger=DEBUG,console
log4j.logger.cn.lacknb.dao.UserDao=DEBUG, console
log4j.additivity.org.apache=true
# 控制台(console)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> %m %x %n