`

spring-boot-mybatis

阅读更多

     最近闲来无事,整合了一下springBoot-Mybatis,确实比springMVC配置简单,闲话不说了,看代码

一、结构:

 二、配置文件

1.pom.xml

<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.lyc</groupId>
  <artifactId>spring-boot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.8.RELEASE</version>
  </parent>
  
  <!-- build配置 -->
  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
  </properties>
  
  <dependencies>
  	<!--Spring Boot配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
	<!--模板引擎-->
    	<dependency>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-thymeleaf</artifactId>
    	</dependency>
    
    <!--支持使用 JDBC 访问数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        
    <!--添加适用于生产环境的功能,如性能指标和监测等功能。 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
    <!--Mysql / DataSource-->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
     <!--Json Support-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.43</version>
        </dependency>
     <!--Swagger support-->
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>0.9.5</version>
        </dependency>
  </dependencies>
  
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
  <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestone</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

 2.application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=8011

 由于springBoot自带tomcat,默认端口8080,不便有调试,所以修改端口server.port=8011

3、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.lyc.dao.UserMapperDao">
 
  <select id="getAllUserInfo" resultType="com.lyc.model.User">
    select name, age,password from user;
  </select>
  
  <select id="findUserInfo" resultType="com.lyc.model.User">
    select name, age,password from user where age = #{couponNo};
  </select>
 
</mapper>

4.实体类user

package com.lyc.model;

public class User {
	public int id;
	public String name;
	public int age;
	public String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

  

5.userMapperDao

package com.lyc.dao;

import java.util.List;

import com.lyc.model.User;

public interface  UserMapperDao {
	//findUserInfo
	public User findUserInfo(int age);
	
	//getAllUserInfo
	public List<User> getAllUserInfo();
	
}

 6.UserController.java

package com.lyc.controller;
 

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.lyc.dao.UserMapperDao;
import com.lyc.model.User;
 
@Controller
public class UserController {
 
    private Logger logger = Logger.getLogger(UserController.class);
 
    @Autowired
    private UserMapperDao userMapperDao;
 
    @RequestMapping("/getAllUserInfo")
    @ResponseBody
    public List<User> getAllUserInfo() {
    	List<User> user = userMapperDao.getAllUserInfo();
        if(user!=null){
        	System.out.println("size:"+user.size());
        	logger.info("size:"+user.size());
        }
        return user;
    }
    
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public User getUserInfo() {
    	int age = Integer.parseInt(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getParameter("age"));
    	
        User user = userMapperDao.findUserInfo(age);
        if(user!=null){
            System.out.println("user.getName():"+user.getName());
            logger.info("user.getAge():"+user.getAge());
        }
        return user;
    }
}

 7.启动类,我命名成了demo

package com.lyc;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
 
import javax.sql.DataSource;
 
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan("com.lyc.dao")
public class demo {
    private static Logger logger = Logger.getLogger(demo.class);
 
    //DataSource配置
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
 
    //提供SqlSeesion
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
 
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
 
    /**
     * Main Start
     */
    public static void main(String[] args) {
        SpringApplication.run(demo.class, args);
        logger.info("============= SpringBoot Start Success =============");
    }
 
}

 数据库就不写了,很简单的一个

 

 

这样我们就配置好了,让我们启动一下看效果,这里值得注意的是,我们不需要写项目名称,因为在main方法中已经内嵌了一下tomcat



 

---------我只是分隔一下,怕看不情况-----------



 

好的,完成。

如果需要源码去我的git上面下载,https://github.com/Abel-Li/Spring-boot.git

 

 

  • 大小: 24.6 KB
  • 大小: 5.5 KB
  • 大小: 28.3 KB
  • 大小: 34.7 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics