Commit 8912b443 authored by zhangshuhao's avatar zhangshuhao

# Mybatis2

parent f0751525
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.training</groupId>
<artifactId>mybatis2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisTraining</name>
<properties>
<spring.version>4.3.8.RELEASE</spring.version>
<spring.boot.version>1.5.10.RELEASE</spring.boot.version>
<spring.security.version>4.2.3.RELEASE</spring.security.version>
<junit.version>4.12</junit.version>
<jdk.version>1.8</jdk.version>
<jsp.version>2.2</jsp.version>
<servlet.version>3.1.0</servlet.version>
<jstl.version>1.2</jstl.version>
<slf4j-version>1.7.25</slf4j-version>
<hamcrest.core.version>1.3</hamcrest.core.version>
<mockito.core.version>2.8.9</mockito.core.version>
</properties>
<dependencies>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument-tomcat</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<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>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.5.3.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring01</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
MybatisTest.java 测试 selectUser , insertUser 方法
MybatisTest.java 测试 selectUser , insertUser 方法
package com.Config;
package com.Config;
import com.Mapper.*;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
public class AppConfig1 {
@Bean
public DruidDataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/import_server?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai");
ds.setUsername("root");
ds.setPassword("root");
ds.setInitialSize(5);
return ds;
}
//
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
// @Bean
// public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
// return new SqlSessionTemplate(sqlSessionFactory);
// }
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:bean/UserMapper.xml"));
sessionFactory.setTypeAliasesPackage("com/Domain"); // 扫包
// 配置路径
sessionFactory.setConfigLocation(new ClassPathResource("sqlMapConfig.xml"));
return sessionFactory.getObject();
}
// 包扫描
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mScannerConfigurer = new MapperScannerConfigurer();
mScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mScannerConfigurer.setBasePackage("com/Mapper"); // 扫mapper
// 只扫描test.class 类型注解的mapper
// mScannerConfigurer.setAnnotationClass(test.class);
return mScannerConfigurer;
}
}
\ No newline at end of file
package com.Config;
package com.Config;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
@Intercepts(
{
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
}
)
public class CustomPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey = null;
BoundSql boundSql = null;
Class<?> type = ms.getParameterMap().getType();
if (args.length >= 4) {
boundSql = ms.getBoundSql(parameter);
ResultHandler resultHandler = (ResultHandler) args[3];
RowBounds rowBounds = (RowBounds) args[2];
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
if (args.length == 6) {
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
String sql = getSql(boundSql, type);
//log.debug("runing query(dql) sql:{}", sql);
return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
} else if (args.length == 2) {
// update
boundSql = ms.getBoundSql(parameter);
String sql = getSql(boundSql, type);
//log.debug("runing update(dml) sql:{}", sql);
return executor.update(ms, parameter);
} else {
throw new RuntimeException("无效拦截");
}
}
private String getSql(BoundSql boundSql, Class<?> type) {
String sql = boundSql.getSql();
final String[] temp = {sql};
if (sql.contains("?") && boundSql.getParameterMappings().size() > 0 && boundSql.getParameterObject() != null) {
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
Object parameterObject = boundSql.getParameterObject();
//多参数
if (parameterObject instanceof HashMap) {
MapperMethod.ParamMap parameterObject1 = (MapperMethod.ParamMap) parameterObject;
parameterMappings.forEach(parameters -> {
String property = parameters.getProperty();
// todo 拦截过滤,大小过滤
String strs = String.valueOf(parameterObject1.get(property));
if (strs != null) {
temp[0] = temp[0].replaceFirst("\\?", "'" + strs + "'");
}
});
} else if (parameterObject instanceof String) {
// 单参数
parameterMappings.forEach(parameters -> {
// todo 拦截过滤,大小过滤
String strs = String.valueOf(parameterObject);
temp[0] = temp[0].replaceFirst("\\?", "'" + strs + "'");
});
} else if (parameterObject.getClass().isAssignableFrom(type)) {
// 对象类型
String ss = parameterObject.toString();
String substring = ss;
String[] strings = new String[1];
strings[0] = ss;
substring = substring.replaceFirst("\\(", "");
substring = substring.replaceFirst("\\)", "");
if (substring.contains("(") || substring.contains(")")) {
// 不管, 显示全部j对象数据
} else {
substring = strings[0];
substring = substring.replaceAll(" ", "");
HashMap<String, String> map = new HashMap<>();
int i = substring.indexOf("(");
int i1 = substring.lastIndexOf(")");
if (i != -1 && i1 != -1) {
substring = substring.substring(i + 1, i1);
}
// 若不存在复合类型的精准提供
String[] split = substring.split(",");
if (split.length > 0) {
for (String s : split) {
int i2 = s.indexOf("=");
String key = s.substring(0, i2);
String value = s.substring(i2 + 1);
map.put(key, value);
}
}
parameterMappings.forEach(parameters -> {
String property = parameters.getProperty();
String strs = String.valueOf(map.get(property));
temp[0] = temp[0].replaceFirst("\\?", "'" + strs + "'");
});
}
}
}
//TODO 自己要进行的各种处理
return temp[0];
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
//
}
}
package com.Config;
package com.Config;
import com.Domain.Context;
import com.Domain.User;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by lqt
*/
@MappedTypes({Context.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class MyTypeHandler implements TypeHandler<Context> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, Context user, JdbcType jdbcType) throws SQLException {
System.out.println("自定义类型转换");
String s = JSONObject.toJSONString(user);
preparedStatement.setString(i, s);
}
@Override
public Context getResult(ResultSet rs, String columnName) throws SQLException {
System.out.println("自定义类型转换");
String string = rs.getString(columnName);
return JSONObject.parseObject(string, Context.class);
}
@Override
public Context getResult(ResultSet rs, int columnIndex) throws SQLException {
System.out.println("自定义类型转换");
String string = rs.getString(columnIndex);
return JSONObject.parseObject(string, Context.class);
}
@Override
public Context getResult(CallableStatement cs, int columnIndex) throws SQLException {
System.out.println("自定义类型转换");
String string = cs.getString(columnIndex);
return JSONObject.parseObject(string, Context.class);
}
}
package com.Controller;
package com.Controller;
import com.Domain.User;
import com.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by lqt
*/
@RestController
public class Controller {
@Autowired
UserService userService;
@RequestMapping("insertUser")
public void save(@RequestBody User user) {
userService.insertUser(user);
}
@RequestMapping("insertUserNoObject")
public void insertUserNoObject(@RequestBody User user) {
userService.insertUserNoObject(user);
}
@GetMapping("insert")
public void transactionTestWithInsert() {
userService.insert();
}
@GetMapping("select")
public ResponseEntity transactionTestWithSelect() {
return ResponseEntity.ok(userService.findUser().size());
}
@GetMapping("selectByOne")
public ResponseEntity transactionTestWithSelectByOne() {
String name = "pop0";
return ResponseEntity.ok(userService.selectUserByUsername(name).size());
}
@GetMapping("selectOne")
public void selectUser() {
String name = "username";
String password = "123";
User user = userService.selectUser(name, password);
System.out.println(user);
}
}
package com.Domain;
package com.Domain;
public class Context {
private String username;
private String password;
private Boolean enabled;
private String context;
public Context() {
}
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 Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
\ No newline at end of file
package com.Domain;
package com.Domain;
public class User {
private String username;
private String password;
private Boolean enabled;
private Context context;
public User() {
}
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 Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
\ No newline at end of file
package com.Mapper;
package com.Mapper;
import com.Domain.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@test
public interface UserMapper {
public void insert(User user);
public User selectUser(@Param(value = "username") String userName, @Param(value = "password")String password);
public List<User> selectUserByUsername(String userName);
public List<User> selectAll();
User findOne(String username);
}
\ No newline at end of file
package com.Mapper;
package com.Mapper;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by lqt
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface test {
String value() default "";
}
package com.Service;
package com.Service;
import com.Domain.Context;
import com.Domain.User;
import com.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* cglib 代理 Created by lqt
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
// 脏读
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void insert() {
User user = new User();
user.setUsername("hch");
user.setPassword("123");
user.setEnabled(true);
Context build = new Context();
build.setUsername("hcj");
build.setPassword("123");
build.setContext("hello world");
build.setEnabled(true);
user.setContext(build);
userMapper.insert(user);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException();
}
public void insertUser(User user) {
user.setEnabled(true);
Context build = new Context();
build.setUsername("hcj");
build.setPassword("123");
build.setContext("hello world");
build.setEnabled(true);
user.setContext(build);
user.setContext(build);
userMapper.insert(user);
}
// @Transactional(readOnly = true)
public List<User> findUser() {
return userMapper.selectAll();
}
public User selectUser(String username, String password) {
return userMapper.selectUser(username, password);
}
public List<User> selectUserByUsername(String username) {
return userMapper.selectUserByUsername(username);
}
public void insertUserNoObject(User user) {
user.setEnabled(true);
userMapper.insert(user);
}
}
package com;
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 开启 springboot Created by lqt on 18-7-10
*/
@EnableTransactionManagement
@SpringBootApplication
public class StartUp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(StartUp.class);
app.run(args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD com.Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Mapper.UserMapper"> <!--mapper -->
<resultMap type="user" id="userList">
<!-- type为返回列表元素的类全名或别名 -->
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="enabled" property="enabled"/>
<result column="context" property="context"
typeHandler="com.Config.MyTypeHandler"/>
</resultMap>
<insert id="insert" parameterType="user">
insert into users(username,
password,enabled,context) values(#{username}, #{password},#{enabled},#{context})
</insert>
<select id="selectUser" parameterType="String" resultType="user">
SELECT #{username},#{password} FROM users WHERE username = #{username} and password=#{password}
</select>
<select id="selectUserByUsername" parameterType="String" resultType="user">
SELECT #{username} FROM users WHERE username = #{username}
</select>
<select id="selectAll" resultMap="userList">
SELECT * FROM users
</select>
</mapper>
\ No newline at end of file
# ===================================================================
# ===================================================================
# Spring Boot configuration for the "dev" profile.
#
# This configuration overrides the application.yml file.
#
# More information on profiles: http://www.jhipster.tech/profiles/
# More information on configuration properties: http://www.jhipster.tech/common-application-properties/
# ===================================================================
# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================
# springboot 提供的日志,
logging:
level:
ROOT: DEBUG
# spittr: DEBUG
# file: my.log
spring:
profiles:
active: StartUp
jackson:
serialization.indent_output: true
redis:
port: 6379
database: 7
lettuce:
pool:
max-active: 10
min-idle: 3
max-idle: 8
# mail:
# host: mail.mso-china.com
# port: 25
# username: Tom.hou@mso-china.com
# password: woaini111
server:
port: 8081
address: 0.0.0.0
#mailServer:
# from: Tom.hou@mso-china.com
# to: Tom.hou@mso-china.com
# backupfile: /home/hcj/backup/
\ No newline at end of file
spring:
spring:
application:
name: StartUp
profiles:
active: preprodtest
info:
project:
version: 1.0 #project.version# kerberosprod preprod
application:
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD com.Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--<setting name="cacheEnabled" value="true"/>-->
<!--<setting name="lazyLoadingEnabled" value="true"/>-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--<setting name="defaultExecutorType" value="BATCH"/>-->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<typeHandlers>
<typeHandler handler="com.Config.MyTypeHandler" jdbcType="VARCHAR" javaType="com.Domain.Context"/>
</typeHandlers>
<plugins>
<plugin interceptor="com.Config.CustomPlugin"/>
</plugins>
<!--<plugins>-->
<!--<plugin interceptor="com.Mapper.MyPlugins">-->
<!--<property name="dbType" value="Mysql"/>-->
<!--</plugin>-->
<!--<plugin interceptor="com.github.pagehelper.PageHelper">-->
<!--<property name="dialect" value="mysql"/>-->
<!--<property name="offsetAsPageNum" value="false"/>-->
<!--<property name="rowBoundsWithCount" value="false"/>-->
<!--<property name="pageSizeZero" value="true"/>-->
<!--<property name="reasonable" value="false"/>-->
<!--<property name="supportMethodsArguments" value="false"/>-->
<!--<property name="returnPageInfo" value="none"/>-->
<!--</plugin>-->
<!--<plugin interceptor="com.Mapper.SelectLimitPlugins">-->
<!--<property name="limit" value="1"/>-->
<!--</plugin>-->
<!--<plugin interceptor="com.Mapper.PagePlugins">-->
<!--<property name="page" value="1"/>-->
<!--<property name="pageSize" value="5"/>-->
<!--<property name="useFlag" value="true"/>-->
<!--<property name="checkFlag" value="true"/>-->
<!--</plugin>-->
<!--</plugins>-->
</configuration>
\ No newline at end of file
package transaction;
package transaction;
import com.Config.AppConfig1;
import com.Domain.Context;
import com.Domain.User;
import com.Mapper.UserMapper;
import com.Service.UserService;
import com.StartUp;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* Created by lqt
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {StartUp.class})
public class MybatisTest {
private static final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
@Autowired
UserService userService;
//=====================================mybatis 2 homework start=============================================================
/**
* 提供单对象,和多对象参数, sql打印功能 => 查询
*/
@Test
public void selectUser() {
String name = "hcj";
User user = userService.selectUser(name, "123");
System.out.println(user);
}
/**
* 提供单对象,, sql打印功能 => 修改删除,新增, 注意: 目前多对象参数暂不支持
*/
@Test
public void insertUser() {
User user = new User();
user.setUsername("张三");
user.setPassword("000000");
user.setEnabled(true);
userService.insertUserNoObject(user);
}
}
-- test
-- test
CREATE TABLE `users` (
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`enabled` bit(1) DEFAULT NULL,
`context` varchar(1000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment