Commit afbb0a97 authored by 杨伊博's avatar 杨伊博

springboot-mybatis is ok

parent 7611e9ba
<?xml version="1.0" encoding="UTF-8"?>
<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.u</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.us.Application</start-class>
<mybatis.version>3.2.7</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!--util-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.us.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.*;
/**
* Created by yangyibo on 17/1/17.
*/
@ComponentScan(basePackages ="com.us.example")
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
\ No newline at end of file
package com.us.example.bean;
import java.util.Date;
public class User {
private Integer id;
/** The name. */
private String name;
/** The password. */
private String password;
/** The rePassword. */
private String rePassword;
/** The username. */
private String username;
/** The division id. */
private Integer divisionId;
/** The email. */
private String email;
/** The gender. */
private String gender;
/** The mobilephone. */
private String mobilephone;
/** The telephone. */
private String telephone;
/** The user type. */
private Integer userType;
/** The create by. */
private String createBy;
/** The create time. */
private Date createTime;
/** The update by. */
private String updateBy;
/** The update time. */
private Date updateTime;
/** The disabled. */
private Integer disabled;
/** The theme. */
private String theme;
/** The is ldap. */
private Integer isLdap;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* Get the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Set the name.
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the re password.
*
* @return the re password
*/
public String getRePassword()
{
return rePassword;
}
/**
* Set the re password.
*
* @param rePassword the re password
*/
public void setRePassword(String rePassword)
{
this.rePassword = rePassword;
}
/**
* Get the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Set the password.
*
* @param password the password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get the username.
*
* @return the username
*/
public String getUsername() {
return username;
}
/**
* Set the username.
*
* @param username the username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Get the division id.
*
* @return the division id
*/
public Integer getDivisionId() {
return divisionId;
}
/**
* Set the division id.
*
* @param divisionId the division id
*/
public void setDivisionId(Integer divisionId) {
this.divisionId = divisionId;
}
/**
* Get the email.
*
* @return the email
*/
public String getEmail() {
return email;
}
/**
* Set the email.
*
* @param email the email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the gender.
*
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* Set the gender.
*
* @param gender the gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Get the mobilephone.
*
* @return the mobilephone
*/
public String getMobilephone() {
return mobilephone;
}
/**
* Set the mobilephone.
*
* @param mobilephone the mobilephone
*/
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
/**
* Get the telephone.
*
* @return the telephone
*/
public String getTelephone() {
return telephone;
}
/**
* Set the telephone.
*
* @param telephone the telephone
*/
public void setTelephone(String telephone) {
this.telephone = telephone;
}
/**
* Get the user type.
*
* @return the user type
*/
public Integer getUserType() {
return userType;
}
/**
* Set the user type.
*
* @param userType the user type
*/
public void setUserType(Integer userType) {
this.userType = userType;
}
/**
* Get the creates the by.
*
* @return the creates the by
*/
public String getCreateBy() {
return createBy;
}
/**
* Set the creates the by.
*
* @param createBy the creates the by
*/
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
/**
* Get the creates the time.
*
* @return the creates the time
*/
public Date getCreateTime() {
return createTime;
}
/**
* Set the creates the time.
*
* @param createTime the creates the time
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* Get the update by.
*
* @return the update by
*/
public String getUpdateBy() {
return updateBy;
}
/**
* Set the update by.
*
* @param updateBy the update by
*/
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
/**
* Get the update time.
*
* @return the update time
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* Set the update time.
*
* @param updateTime the update time
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* Get the disabled.
*
* @return the disabled
*/
public Integer getDisabled() {
return disabled;
}
/**
* Set the disabled.
*
* @param disabled the disabled
*/
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
/**
* Get the theme.
*
* @return the theme
*/
public String getTheme() {
return theme;
}
/**
* Set the theme.
*
* @param theme theme
*/
public void setTheme(String theme) {
this.theme = theme;
}
/**
* Get the checks if is ldap.
*
* @return the checks if is ldap
*/
public Integer getIsLdap()
{
return isLdap;
}
/**
* Set the checks if is ldap.
*
* @param isLdap the checks if is ldap
*/
public void setIsLdap(Integer isLdap)
{
this.isLdap = isLdap;
}
}
\ No newline at end of file
package com.us.example.config;
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
public class DBConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("ms.db.url"));
dataSource.setUser(env.getProperty("ms.db.username"));
dataSource.setPassword(env.getProperty("ms.db.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
package com.us.example.config;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// sessionFactory.setPlugins(new Interceptor[]{new PageInterceptor()});
sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));
return sessionFactory;
}
}
package com.us.example.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//@Retention: 定义注解的保留策略,注释类型的注释要保留
@Retention(RetentionPolicy.RUNTIME)
//@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
//作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
//取值(ElementType)有:
//CONSTRUCTOR:用于描述构造器
//2.FIELD:用于描述域
//3.LOCAL_VARIABLE:用于描述局部变量
//4.METHOD:用于描述方法
//5.PACKAGE:用于描述包
//6.PARAMETER:用于描述参数
//7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Target(ElementType.TYPE)
public @interface MyBatisRepository {
}
package com.us.example.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisScannerConfig {
@Bean
public MapperScannerConfigurer MapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.us.example.dao");
mapperScannerConfigurer.setAnnotationClass(MyBatisRepository.class);
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
package com.us.example.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
@ComponentScan
public class TransactionConfig implements TransactionManagementConfigurer{
@Autowired
private DataSource dataSource;
@Bean(name = "transactionManager")
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
\ No newline at end of file
package com.us.example.controller;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.us.example.service.UserService;
import com.us.example.util.CommonUtil;
/**
*
* @ClassName UserController
* @author abel
* @date 2016年11月10日
*/
@Controller
@RequestMapping(value = "/users")
public class UserController {
private static final Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
/***
* api :localhost:8099/users?id=99
*
* @param request
* @return
*/
@RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<Object> list(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
return new ResponseEntity<>(userService.getList(map), HttpStatus.OK);
}
}
\ No newline at end of file
package com.us.example.dao;
import java.util.List;
import java.util.Map;
import com.us.example.bean.User;
import com.us.example.config.MyBatisRepository;
@MyBatisRepository
public interface UserDao {
public List<User> getList(Map<String,Object> map);
}
package com.us.example.service;
import java.util.Map;
import com.us.example.bean.User;
/**
* The Interface UserService.
*/
public interface UserService {
/**
* Gets the list.
*
* @param map the map
* @return the list
*/
public Object getList(Map<String, Object> map);
}
\ No newline at end of file
package com.us.example.serviceImpl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.us.example.dao.UserDao;
import com.us.example.service.UserService;
/**
*
* @ClassName UserServiceImpl
* @author abel
* @date 2016年11月10日
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
/**
*
* @param map
* @return
*/
public Object getList(Map<String, Object> map) {
return userDao.getList(map);
}
}
\ No newline at end of file
package com.us.example.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
public class CommonUtil {
/**
* 从request中获得参数Map,并返回可读的Map.
*
* @param request the request
* @return the parameter map
*/
public static Map<String, Object> getParameterMap(HttpServletRequest request) {
// 参数Map
Map<String, String[]> properties = request.getParameterMap();
//返回值Map
Map<String, Object> returnMap = new HashMap<String, Object>();
Set<String> keySet = properties.keySet();
for(String key: keySet){
String[] values = properties.get(key);
String value = "";
if(values != null && (values.length==1&&StringUtils.isNotBlank(values[0]))?true:false){
for(int i=0;i<values.length;i++){
if(values[i] != null && !"".equals(values[i])){
// value = new String(values[i].getBytes("ISO-8859-1"),"UTF-8") + ",";
value += values[i] + ",";
}
}
if(value != null && !"".equals(value)){
value = value.substring(0, value.length()-1);
}
if(key.equals("keywords")){//关键字特殊查询字符转义
value = value.replace("_", "\\_").replace("%", "\\%");
}
returnMap.put(key, value);
}
}
return returnMap;
}
}
# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8099
ms.db.driverClassName=com.mysql.jdbc.Driver
ms.db.url=jdbc:mysql://localhost:3306/msm?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true
ms.db.username=root
ms.db.password=admin
ms.db.maxActive=500
\ No newline at end of file
# Output pattern : date [thread] priority category - message
log4j.rootLogger=INFO, Console, R
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=logs/cmbms.log
log4j.appender.R.MaxFileSize=20MB
log4j.appender.R.MaxBackupIndex=30
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#Project defalult level
log4j.logger.com.us=INFO
#spring default level
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.jdbc=INFO
#apache
log4j.logger.org.apache=INFO
log4j.logger.org.activiti=INFO
log4j.logger.org.activiti.engine.impl.persistence.entity=INFO
log4j.logger.org.activiti.spring.SpringTransactionInterceptor=ERROR
#mybatis, debug level to see sql
log4j.logger.com.us.cmbms.dao=DEBUG
log4j.logger.com.us.workflow.dao=DEBUG
<?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.us.example.dao.UserDao">
<resultMap id="userMap" type="com.us.example.bean.User">
<id property="id" column="ID" />
<result property="name" column="NAME" />
<result property="password" column="PASSWORD" />
<result property="username" column="USERNAME" />
<result property="divisionId" column="DIVISION_ID" />
<result property="email" column="EMAIL" />
<result property="gender" column="GENDER" />
<result property="mobilephone" column="MOBILEPHONE" />
<result property="telephone" column="TELEPHONE" />
<result property="userType" column="USER_TYPE" />
<result property="createBy" column="CREATE_BY" />
<result property="createTime" column="CREATE_TIME" />
<result property="updateBy" column="UPDATE_BY" />
<result property="updateTime" column="UPDATE_TIME" />
<result property="disabled" column="DISABLED" />
<result property="theme" column="THEME" />
<result property="isLdap" column="IS_LDAP" />
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and ID = #{id}
</if>
<if test="name != null and name != ''">
and NAME = #{name}
</if>
<if test="password != null and password != ''">
and PASSWORD = #{password}
</if>
<if test="username != null and username != ''">
and USERNAME = #{username}
</if>
<if test="divisionId != null and divisionId != ''">
and DIVISION_ID = #{divisionId}
</if>
<if test="email != null and email != ''">
and EMAIL = #{email}
</if>
<if test="gender != null and gender != ''">
and GENDER = #{gender}
</if>
<if test="mobilephone != null and mobilephone != ''">
and MOBILEPHONE = #{mobilephone}
</if>
<if test="telephone != null and telephone != ''">
and TELEPHONE = #{telephone}
</if>
<if test="userType != null and userType != ''">
and USER_TYPE = #{userType}
</if>
<if test="disabled != null and disabled != ''">
and DISABLED = #{disabled}
</if>
<if test="theme != null and theme != ''">
and THEME = #{theme}
</if>
<if test="keywords != null and keywords != ''">
and (name like CONCAT('%', #{keywords},'%') OR username
like CONCAT('%', #{keywords},'%')
OR telephone like CONCAT('%', #{keywords},'%') OR email like
CONCAT('%', #{keywords},'%') )
</if>
</where>
</sql>
<select id="getList" parameterType="map" resultMap="userMap">
SELECT * FROM sec_user
<include refid="queryCondition" />
order by create_time desc
</select>
</mapper>
\ 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