zoukankan      html  css  js  c++  java
  • springboot-简单集成mybatis

    Spring Boot 集成Mybatis:
    ---------------------------------------
    1、新建一个新的Maven Project;
    2、需要在pom.xml文件添加相应的依赖,
    比如:mysql驱动;
    PageHelper分页插件,需要版本号;
    3、编写启动类,大部分和之前的代码是一样的,需要的注意的是:
    需要添加一个注解@MapperScan --指定MyBatis持久类的位置;
    4、编写一个测试的实体类Student;
    5、编写一个StudentMapper,使用@Select和@Save进行数据库操作;
    使用@Options配置返回的主键信息;
    6、编写StudentService;
    7、编写StudentController;
    8、添加分页配置信息,需要添加一个MyBatisConfiguration;
    9、使用PageHelper.startPage(pageNum,pageSize)进行分页;

    1.pom文件

    <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.it.huanyu</groupId>
    	<artifactId>spring-boot-mybatis1</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>spring-boot-mybatis1</name>
    	<url>http://maven.apache.org</url>
    	  <!-- spring boot parent节点,引入这个之后,在下面和spring boot相关的就不需要引入版本了; -->
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.4.1.RELEASE</version>
    	</parent>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<!-- 指定一下jdk的版本 ,这里我们使用jdk 1.8 ,默认是1.6 -->
    		<java.version>1.8</java.version>
    
    	</properties>
    
    	<dependencies>
    		<!-- web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ........ -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		
    		 <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
               <scope>true</scope>
            </dependency>
    
    		<!-- mysql 数据库驱动. -->
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    		</dependency>
    
    		<!-- spring-boot mybatis依赖: 请不要使用1.0.0版本,因为还不支持拦截器插件, 1.1.1 是博主写帖子时候的版本,大家使用最新版本即可 -->
    		<dependency>
    			<groupId>org.mybatis.spring.boot</groupId>
    			<artifactId>mybatis-spring-boot-starter</artifactId>
    			<version>1.1.1</version>
    		</dependency>
    
    
    		<!-- MyBatis提供了拦截器接口,我们可以实现自己的拦截器, 将其作为一个plugin装入到SqlSessionFactory中。 Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。 
    			Github项目地址: https://github.com/pagehelper/Mybatis-PageHelper -->
    		<dependency>
    			<groupId>com.github.pagehelper</groupId>
    			<artifactId>pagehelper</artifactId>
    			<version>4.1.0</version>
    		</dependency>
    		<!-- 添加Spring-data-jpa依赖. -->
    		<dependency>
    		    <groupId>org.springframework.boot</groupId>
    		    <artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    				<configuration>
    					<!--fork : 如果没有该项配置,devtools不会起作用,即应用不会restart -->
    					<fork>true</fork>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    

      

    2.启动类

    package com.it.huanyu.spring_boot_mybatis1;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * Hello world!
     *
     */
    @SpringBootApplication
    @MapperScan("com.it.huanyu.*")
    public class App 
    {
        public static void main( String[] args )
        {
        	System.err.println("hellowaa");
        	SpringApplication.run(App.class, args);
        }
    }
    

      

    3.实体类

    package com.it.huanyu.spring_boot_mybatis1;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Student {
    	
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	private Integer id;
    	
    	private String name;
    	private String remarks;
    
    	public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getRemarks() {
    		return remarks;
    	}
    
    	public void setRemarks(String remarks) {
    		this.remarks = remarks;
    	}
    	
    	
    
    }
    

      

    4.数据库和jpa使用配置application.properties

    ########################################################
    ###datasource
    ########################################################
    spring.datasource.url = jdbc:mysql://localhost:3306/test
    spring.datasource.username = root
    spring.datasource.password = 123
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.max-active=20
    spring.datasource.max-idle=8
    spring.datasource.min-idle=8
    spring.datasource.initial-size=10
    ########################################################
    ### Java Persistence Api --  Spring jpau7684u914Du7F6Eu4FE1u606F.
    ########################################################
    # Specify the DBMS
    spring.jpa.database = MYSQL
    # Show or not log for each sql query
    spring.jpa.show-sql = true
    # Hibernate ddl auto (create, create-drop, update)
    spring.jpa.hibernate.ddl-auto = update
    # Naming strategy
    #[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]
    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
    # stripped before adding them to the entity manager)
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
    

      

    5.StudentMapper

    package com.it.huanyu.spring_boot_mybatis1;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Options;
    import org.apache.ibatis.annotations.Select;
    
    public interface StudentMapper {
    	
    	@Select("select *from Student where name like #{name}")
    	public List<Student> queryAll(String name) ;
    	@Select("select *from Student where id = #{id}")
    	public Student getById(Integer id);
    	
    	@Select("select name from Student where id = #{id}")
    	public String getNameById(long id);
    	@Insert("insert into Student(name,remarks) values(#{name},#{remarks})  ")
    	@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
    	public void insert(Student stu);
    
    }
    

      

    6.StudentService

    package com.it.huanyu.spring_boot_mybatis1;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class StudentService {
    	
    	@Autowired
    	private StudentMapper studentMapper;
    	
    	public List<Student> queryAll(String name) {
    		return studentMapper.queryAll(name);
    	}
    	@Transactional
    	public void insert(Student stu) {
    		studentMapper.insert(stu);
    		
    	}
    }
    

      

    7.StudentController

    package com.it.huanyu.spring_boot_mybatis1;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.github.pagehelper.PageHelper;
    
    @RestController
    public class StudentController {
    	@Autowired
    	private StudentService studentService;
    	
    	/**
    	 * 查詢
    	 */
    	@RequestMapping("/queryAll")
    	public List<Student> queryAll(String name){
    		PageHelper.startPage(2, 1);
    		return studentService.queryAll(name);
    	}
    	/**
    	 * Tina及
    	 */
    	@RequestMapping("/insert")
    	public Student insert(){
    		Student stu=new Student();
    		stu.setName("lisi");
    		stu.setRemarks("猪队友");
    		studentService.insert(stu);
    		return stu;
    		
    	}
    	
    }
    

      

    8.PageHelper分页插件

    package com.it.huanyu.spring_boot_mybatis1;
    
    import java.util.Properties;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import com.github.pagehelper.PageHelper;
    
    @Configuration
    public class MyBatisConfiguration {
    	
    	@Bean
        public PageHelper pageHelper() {
    		System.out.println("MyBatisConfiguration.pageHelper()");
            PageHelper pageHelper = new PageHelper();
            Properties p = new Properties();
            p.setProperty("offsetAsPageNum", "true");
            p.setProperty("rowBoundsWithCount", "true");
            p.setProperty("reasonable", "true");
            pageHelper.setProperties(p);
            return pageHelper;
        }
    }
    

      

  • 相关阅读:
    85. Maximal Rectangle
    120. Triangle
    72. Edit Distance
    39. Combination Sum
    44. Wildcard Matching
    138. Copy List with Random Pointer
    91. Decode Ways
    142. Linked List Cycle II
    异或的性质及应用
    64. Minimum Path Sum
  • 原文地址:https://www.cnblogs.com/liushisaonian/p/9350096.html
Copyright © 2011-2022 走看看