<dependencies>
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--Spring面向切面依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!--Spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybaits依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--spring 数据操作依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--mybatis和spring整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
<!--maven 静态资源管理,主要是为了导出mapper-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
数据库语句:
CREATE TABLE `my_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
INSERT INTO `my_user` VALUES ('1', 'tom', '0', 'tom@163.com');
INSERT INTO `my_user` VALUES ('2', 'king2', '1', 'king2@163.com');
INSERT INTO `my_user` VALUES ('6', 'menglingfeng', '1', 'ff@163.com');
INSERT INTO `my_user` VALUES ('7', 'tom2', '1', 'tom2@163.com');
com\applesnt\vo\UserVo.java
package com.applesnt.vo;
import lombok.Data;
@Data
public class UserVo {
private String lastName;
private String gender;
private String email;
}
com\applesnt\mapper\UserMapper.java
package com.applesnt.mapper;
import com.applesnt.vo.UserVo;
import java.util.List;
public interface UserMapper {
public List<UserVo> getAllUser();
}
com\applesnt\mapper\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接口的全路径-->
<mapper namespace="com.applesnt.mapper.UserMapper">
<select id="getAllUser" resultType="com.applesnt.vo.UserVo" databaseId="mysql">
select u.id,u.last_name,u.gender,u.email from my_user u
</select>
</mapper>
resources\jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:3306/my_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
resources\mybatis-config.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>
<!--
properties:引入数据源properties文件
-->
<properties resource="jdbc.properties"></properties>
<settings>
<!--打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 全局性设置懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 每个属性都按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<!-- 别名 -->
<typeAliases>
<package name="com.applesnt.vo.UserVo"/>
</typeAliases>
<!--environments:环境配置 -->
<!--默认执行的配置 -->
<environments default="dev_mysql">
<!--mysql环境配置 -->
<environment id="dev_mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--读取properties属性 -->
<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>
<!-- databaseIdProvider 支持多数据库厂商
DB_VENDOR:得到数据库厂商的标识 MySQL,Oracle,SQL Server
-->
<databaseIdProvider type="DB_VENDOR">
<!-- 为不同的数据库厂商起别名 -->
<property name="MySQL" value="mysql"/>
</databaseIdProvider>
<!-- mappers 将sql映射注入到全局配置中 -->
<mappers>
<mapper resource="com/applesnt/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
@Test
public void test01() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<UserVo> userList = userMapper.getAllUser();
for (UserVo userVo : userList) {
System.out.println(userVo);
}
}
打印结果:
UserVo(lastName=tom, gender=0, email=tom@163.com)
UserVo(lastName=king2, gender=1, email=king2@163.com)
UserVo(lastName=menglingfeng, gender=1, email=ff@163.com)
UserVo(lastName=tom2, gender=1, email=tom2@163.com)
com\applesnt\vo\UserVo.java
package com.applesnt.vo;
import lombok.Data;
@Data
public class UserVo {
private String lastName;
private String gender;
private String email;
}
com\applesnt\mapper\UserMapper.java
package com.applesnt.mapper;
import com.applesnt.vo.UserVo;
import java.util.List;
public interface UserMapper {
public List<UserVo> getAllUser();
}
com\applesnt\mapper\impl\UserMapperImpl.java
package com.applesnt.mapper.impl;
import com.applesnt.mapper.UserMapper;
import com.applesnt.vo.UserVo;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
/*定义spring-mybatis操作对象*/
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<UserVo> getAllUser() {
UserMapper umapper = sqlSession.getMapper(UserMapper.class);
return umapper.getAllUser();
}
}
com\applesnt\mapper\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接口的全路径-->
<mapper namespace="com.applesnt.mapper.UserMapper">
<select id="getAllUser" resultType="com.applesnt.vo.UserVo">
select u.id,u.last_name,u.gender,u.email from my_user u
</select>
</mapper>
resources\jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:3306/my_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
resources\mybatis-config.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>
<settings>
<!--打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 全局性设置懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 每个属性都按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeAliases>
<package name="com.applesnt.vo.UserVo"/>
</typeAliases>
</configuration>
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--加载jdbc配置文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!--数据源配置 数据源提供者包括:spring、c3p0、dbcp、druid-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置得到SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/applesnt/mapper/UserMapper.xml"></property>
</bean>
<!--配置得到SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--没有set方法 只能通过构造器注入-->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!--实例化业务类-->
<bean id="userMapper" class="com.applesnt.mapper.impl.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"></property>
</bean>
</beans>
@Test
public void test02() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<UserVo> userList = userMapper.getAllUser();
for (UserVo userVo : userList) {
System.out.println(userVo);
}
}
打印结果:
UserVo(lastName=tom, gender=0, email=tom@163.com)
UserVo(lastName=king2, gender=1, email=king2@163.com)
UserVo(lastName=menglingfeng, gender=1, email=ff@163.com)
UserVo(lastName=tom2, gender=1, email=tom2@163.com)
基于Spring整合Mybatis(1)
com\applesnt\mapper\impl\UserMapperImpl2.java
package com.applesnt.mapper.impl;
import com.applesnt.mapper.UserMapper;
import com.applesnt.vo.UserVo;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
/*
* 继承SqlSessionDaoSupport会通过getSqlSession()自动获取SqlSession
* */
@Override
public List<UserVo> getAllUser() {
return getSqlSession().getMapper(UserMapper.class).getAllUser();
}
}
<!--继承了SqlSessionDaoSupport 直接注入sqlSessionFactory-->
<bean id="userMapper2" class="com.applesnt.mapper.impl.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
@Test
public void test02() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
List<UserVo> userList = userMapper.getAllUser();
for (UserVo userVo : userList) {
System.out.println(userVo);
}
}
打印结果:
UserVo(lastName=tom, gender=0, email=tom@163.com)
UserVo(lastName=king2, gender=1, email=king2@163.com)
UserVo(lastName=menglingfeng, gender=1, email=ff@163.com)
UserVo(lastName=tom2, gender=1, email=tom2@163.com)
com\applesnt\vo\UserVo.java
package com.applesnt.vo;
import lombok.Data;
@Data
public class UserVo {
private Integer id;
private String lastName;
private String gender;
private String email;
public UserVo() {
}
public UserVo(String lastName, String gender, String email) {
this.lastName = lastName;
this.gender = gender;
this.email = email;
}
}
com\applesnt\mapper\UserMapper.java
package com.applesnt.mapper;
import com.applesnt.vo.UserVo;
import java.util.List;
public interface UserMapper {
/*查询用户*/
public List<UserVo> getAllUser();
/*添加用户*/
public void addUser(UserVo userVo);
/*删除用户*/
public void deleteUser(String name);
}
com\applesnt\mapper\impl\UserMapperImpl.java
package com.applesnt.mapper.impl;
import com.applesnt.mapper.UserMapper;
import com.applesnt.vo.UserVo;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/*
* 继承SqlSessionDaoSupport会通过getSqlSession()自动获取SqlSession
* */
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
/*模拟事务提交*/
@Override
public List<UserVo> getAllUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
UserVo userVo = new UserVo("xlz","1","xlz@qq.com");
//添加操作
mapper.addUser(userVo);
//删除操作
mapper.deleteUser("xlz");
return mapper.getAllUser();
}
@Override
public void addUser(UserVo userVo) {
}
@Override
public void deleteUser(String name) {
}
}
com\applesnt\mapper\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.applesnt.mapper.UserMapper">
<select id="getAllUser" resultType="com.applesnt.vo.UserVo">
select u.id,u.last_name,u.gender,u.email from my_user u
</select>
<!--添加用户-->
<insert id="addUser" useGeneratedKeys="true" keyProperty="id">
insert into my_user(last_name,gender,email)
values(#{lastName},#{gender},#{email})
</insert>
<!--删除用户(模拟出差 deletes )-->
<delete id="deleteUser">
deletes from my_user where last_name = #{name}
</delete>
</mapper>
resources\jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:3306/my_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
resources\mybatis-config.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>
<settings>
<!--打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 全局性设置懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 每个属性都按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeAliases>
<package name="com.applesnt.vo.UserVo"/>
</typeAliases>
</configuration>
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--加载jdbc配置文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!--数据源配置 数据源提供者包括:spring、c3p、dbcp、druid-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置得到SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/applesnt/mapper/*.xml"></property>
</bean>
<!--配置得到SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--没有set方法 只能通过构造器注入-->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!--实例化业务类-->
<bean id="userMapper" class="com.applesnt.mapper.impl.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
@Test
public void test02() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
userMapper.getAllUser();
}
结果:
添加成功数据提交到数据库 但删除是失败的,并没有事务管理
早spring配置文件中增加事务的配置:
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txpoint" expression="execution(* com.applesnt.mapper.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpoint"></aop:advisor>
</aop:config>
进行测试会发现添加操作数据并没有提交到数据库!!!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章