欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot第一章09---集成Mybatis

程序员文章站 2022-06-13 20:05:58
...

操作步骤:

1.集成Mybatis

2.使用PageHelper分页

3.获取自增长id

第一步:添加依赖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.fjz</groupId>
  <artifactId>spring-boot-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-boot-demo</name>
  <url>http://maven.apache.org</url>

  
    <!-- spring-boot父节点依赖,相关的引入就不需要添加version配置,spring boot会选择最合适的版本进行添加  -->
	<parent>
		<groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>2.1.8.RELEASE</version>
	</parent>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- 指定jdk为1.8,默认为1.6 -->
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
  	<!-- 由于上面spring-boot-starter-parent已经指定了版本号,系统会自动选择合适的版本号,不需要再添加 -->
  	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<!-- 添加fastjson依赖,用它来解析json数据,springboot默认的是Jackson解析json数据,但是这里我们自定义使用fastjson -->
	<dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>fastjson</artifactId>
	    <version>1.2.62</version>
	</dependency>
	
	<!--devtools热部署-->
    <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>

	<!-- mybatis依赖 -->
	<dependency>
	    <groupId>org.mybatis.spring.boot</groupId>
	    <artifactId>mybatis-spring-boot-starter</artifactId>
	    <version>2.1.1</version>
	</dependency>
	
	<!-- pagehelper依赖 -->
	<dependency>
	    <groupId>com.github.pagehelper</groupId>
	    <artifactId>pagehelper-spring-boot-starter</artifactId>
	    <version>1.2.5</version>
	</dependency>
	
   <!-- 添加Spring-boot-starter-data-jpa依赖 -->
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
    
    <!-- 添加thymeleaf的依赖 -->
    <dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
    
    <!-- 添加freemarker的依赖 -->
    <dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>
    
    <!-- servlet依赖 -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <scope>provided</scope>
	</dependency>
	
	<!-- jstl 依赖-->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	</dependency>
	
	<!--tomcat依赖 -->
	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-tomcat</artifactId>
	</dependency>
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
  <!-- 构建节点 -->
  <build>
  	<plugins>
  		<plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
 
  	</plugins>
  </build>
  
</project>

第二步:编写MybatisConfiguration.java(分页用)

springboot第一章09---集成Mybatis

package com.fjz.config;

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("你好");
		PageHelper pageHelper = new PageHelper();
		Properties pro = new Properties();
		pro.setProperty("offsetAsPageNum", "true");
		pro.setProperty("rowBoundsWithCount", "true");
		pro.setProperty("reasonable", "true");
		pageHelper.setProperties(pro);
		return pageHelper;
	}
}

 第三步:编写一个实体类:user.java

springboot第一章09---集成Mybatis

package com.fjz.user.bean;

import java.io.Serializable;

public class User implements Serializable{

	private long id;
	private String name;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}

第四步:编写UserMapper.java

package com.fjz.user.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.fjz.user.bean.User;

public interface UserMapper {

	/**
	 * 模糊查询
	 * @param name
	 * @return
	 */
	@Select("select * from user where name = #{name}")
	public List<User> likeName(String name);
	
	/**
	 * 根据id查询
	 * @param id
	 * @return
	 */
	@Select("select * from user where id = #{id}")
	public User selectById(long id);
	
	/**
	 * 根据id查询name
	 * @param id
	 * @return
	 */
	@Select("select name from user where id = #{id}")
	public String selectNameById(long id);
}

第五步:编写UserService.java

package com.fjz.user.service;


import com.fjz.user.bean.User;
import com.fjz.user.mapper.UserMapper;
import com.github.pagehelper.PageHelper;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 模糊查询
	 * @param name
	 * @return
	 */
	public List<User> likeName(String name){
		
		return userMapper.likeName(name);
	}
}

第六步:编写UserController.java

package com.fjz.user.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fjz.user.bean.User;
import com.fjz.user.service.UserService;
import com.github.pagehelper.PageHelper;

import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 模糊查询
	 * @param name
	 * @return
	 */
	@RequestMapping("/likeName")
	public List<User> likeName(String name){
		//第一页,显示两条数据
		PageHelper.startPage(1, 2);
		return userService.likeName(name);
	}
}

 第七步:编写启动类App.java,并启动

注:这里的注解@MapperScan("com.fjz.*.mapper")需要注意

package com.fjz;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * 用@SpringBootApplication指定这是springboot的启动程序
 * @author fengjinzhu
 *
 */
@SpringBootApplication

//扫描该包下的class,主要是Mybatis 的持久化类
//如果不可以的话,可以将包扩展为com.fjz.*
@MapperScan("com.fjz.*.mapper")
public class App {
	
    public static void main( String[] args ) {
        SpringApplication.run(App.class, args);
    }
}

第八步:测试

springboot第一章09---集成Mybatis

===============此部分为id自增长 ==============

UserMapper.java

/**
     * 添加
     * @param user
     */
    @Insert("insert into user(name) values(#{name})")
    public void save(User user);

UserService.java

@Transactional
    public void save(User user){
        userMapper.save(user);
    }

UserController.java

/**
     * 添加信息
     * @return
     */
    @RequestMapping("/save")
    public User save(){
        User user = new User();
        user.setName("张三");
        userService.save(user);
        return user;
    }

测试:

springboot第一章09---集成Mybatis

但是数据库中却显示:

springboot第一章09---集成Mybatis

比较得知:两张图的id不同

那么怎么解决?

只需要在UserMappe.java中加上注解@Options即可

springboot第一章09---集成Mybatis

 /**
     * 添加
     * @param user
     */
    @Insert("insert into user(name) values(#{name})")
    @Options(useGeneratedKeys =true, keyProperty = "id", keyColumn = "id")
    public void save(User user);

测试得到:id与数据库保持一致

springboot第一章09---集成Mybatis

 

 

 

 

 

相关标签: springboot Mybatis