Commit 6e28295b authored by hou's avatar hou

侯春建作业提交

parent d9c5de54
######################################################################
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/*
nbbuild/
dist/
nbdist/
.nb-gradle/
######################################################################
# Others
*.log
*.xml.versionsBackup
*.txt
!*/build/*.java
!*/build/*.html
!*/build/*.xml
\ No newline at end of file
This diff is collapsed.
1.打开项目执行 transaction.MybatisTest测试用例
2. 另,可通过sql生成数据库表结构, users表
\ No newline at end of file
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 UserMapper userMapper(SqlSessionTemplate sqlSessionTemplate) throws Exception {
// return sqlSessionTemplate.getMapper(UserMapper.class);
// }
// 包扫描
@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 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 hcj on 18-7-18
*/
@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.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.RestController;
/**
* Created by hcj on 18-7-16
*/
@RestController
public class Controller {
@Autowired
UserService userService;
@GetMapping("insert")
public void transactionTestWithInsert() {
userService.insert();
}
@GetMapping("select")
public ResponseEntity transactionTestWithSelect() {
return ResponseEntity.ok(userService.findUser().size());
}
}
package com.Domain;
package com.Domain;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@ToString
@Builder
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Context {
public Context() {
}
public Context(String username, String password, Boolean enabled, String context) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.context = context;
}
private String username;
private String password;
private Boolean enabled;
private String context;
}
\ No newline at end of file
package com.Domain;
package com.Domain;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@ToString
@Builder
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User {
public User() {
}
public User(String username, String password, Boolean enabled, Context context) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.context = context;
}
private String username;
private String password;
private Boolean enabled;
private Context context;
}
\ No newline at end of file
package com.Mapper;
package com.Mapper;
import java.util.List;
import com.Domain.*;
@test
public interface UserMapper {
public void insert(User user);
public User selectUser(String userName);
public List<User> selectAll();
}
\ 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 hcj on 18-7-16
*/
@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 hcj on 18-7-16
*/
@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 = Context.builder().username("hcj").password("123")
.context("hello world").enabled(true).build();
user.setContext(build);
userMapper.insert(user);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException();
}
// 不开启事务
// @Transactional(readOnly = true)
public List<User> findUser() {
return userMapper.selectAll();
}
// public static void main(String[] args) {
// User build = User.builder().username("hcj").password("123")
// .context("hello world").enabled(true).build();
// String s = JSONObject.toJSONString(build);
// System.out.println(s);
//
// }
}
package com;
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 开启 springboot Created by hcj 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 * 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.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 hcj on 18-7-16
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {StartUp.class})
public class MybatisTest {
private static final AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig1.class);
@Autowired
UserService userService;
/**
* 1. 自定义TypeHandler类
*
* @param
* @return void
* @author houchunjian
* @date 2019/12/1 0001 14:01
*/
@Test
public void test() {
List<User> user = userService.findUser();
System.out.println(user);
}
/**
* 1. Mybatis 批量插入数据库代码
*
* @param
* @return void
* @author houchunjian
* @date 2019/12/1 0001 14:01
*/
@Test
public void insertOptimistic() {
SqlSessionFactory sqlSessionFactory = context
.getBean("sqlSessionFactory", SqlSessionFactory.class);
// sqlSession 开启事务。 ExecutorType.REUSE 保证batch 事务的合理使用,
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, TransactionIsolationLevel.READ_COMMITTED);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for (int i = 10; i < 20; i++) {
User user = new User();
user.setUsername("pop" + i);
user.setPassword(i + "");
user.setEnabled(true);
if (i % 2 == 0) {
Context build = Context.builder().username("hcj").password("123")
.context("hello world").enabled(true).build();
build.setContext("hello world: " + i);
user.setContext(build);
} else {
Context build = Context.builder().username("hcj").password("123")
.context("hello world").enabled(true).build();
build.setContext("world: " + i);
user.setContext(build);
}
mapper.insert(user);
}
// 刷新
sqlSession.flushStatements();
}
}
CREATE TABLE `users` (
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