Springboot learning--springboot+maven+mybatis project construction

Today we will build a simple project based on springboot+mybatis+maven, the database used is mysql.

 

Final project directory structure

1. Project Creation

1. Create a new spring project

 

Select Spring Initializr, select the jdk version, and then click Next

Fill in Group, Artifact, Type, select Maven Project and click Next

Add project dependencies, temporarily only need to add Web, Mybatis, Mysql three dependencies, click Next

Select the project path, click Finish, the creation is successful

Then add the mybatis configuration information to the application.properties resource file, and the configuration items will be loaded automatically when the project starts.

 

#mybatis
spring.datasource.url=jdbc:mysql://10.100.50.23/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=round&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis.config-location=classpath:mybatis-config.xml
mybatis.typeAliasesPackage=com.example.entity
mybatis.mapper-locations=classpath:mapper/**/*.xml

 

 

2. A brief introduction to the directory structure

 2.1 java

Needless to say about this. Put the java file we wrote

2.2 resources

Springboot advocates no xml configuration, but it still needs some basic information configuration, such as the setting of sql account password, in order to simplify your account password, you still need to configure it yourself, it can't be automatically generated for you. Therefore, the general configuration files are placed under resources. What are the specific files generated by default and what resources are placed in what files. You can read an article I wrote before about the role of each folder. Detailed explanation of the springboot directory structure

2.3 Switch file

The DemoApplication file is the core switch of springboot.

3. Integration

Requirement: Query all the information of a user from the database and return it to the front page

Well, the above makes a simple statement. Start integrating. Or based on the most basic three-tier framework for development

The database is as follows 


 

 

 

3.1 User (create an object to receive the queried data)

 

package com.example.entity;

import java.io.Serializable;

/**
 * SpringBootDemo1
 *
 * @author zhenhai.zheng
 * @date 2018年1月25日 11:25:38
 */
public class User implements Serializable{

    private static final long serialVersionUID = 934073895746700367L;
    private String id;
    private String name;
    private Integer age;

    public User() {
    }

    public User(Integer age, String id, String name) {
        super();
        this.age = age;
        this.id = id;
        this.name = name;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.2 Dao layer creation interface

 

 

package com.example.dao;

import com.example.entity.User;
import org.springframework.stereotype.Repository;

/**
 * @author Hai
 */
@Repository
public interface UserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

3.3 service interface and implementation class

 

 

package com.example.service;

import com.example.entity.User;

/**
 * Created by Hai on 2018/1/18.
 */

public interface UserService {
    void save(User user);
    User getUser(String id);
    boolean updateByPrimaryKey(User user);
    boolean deleteByPrimaryKey(String id);
}
package com.example.service.impl;

import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Hai on 2018/1/18.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void save(User user) {
        userDao.insert(user) ;
    }

    @Override
    public User getUser(String id){
        return userDao.selectByPrimaryKey(Integer.valueOf(id));
    }

    @Override
    public boolean updateByPrimaryKey(User user) {
        return userDao.updateByPrimaryKey(user) > 0;
    }

    @Override
    public boolean deleteByPrimaryKey(String id) {
        return userDao.deleteByPrimaryKey(Integer.valueOf(id)) > 0;
    }
}


3.4 controller layer

 

 

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * SpringBootDemo
 * Created by hai on 2018年1月15日 14:27:32
 */
@RestController
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    /**
     * 保存user信息
     * @param id
     * @param name
     * @param age
     */
    @RequestMapping("/set")
    public void set(String id,String name,int age){
        User user = new User(age,id,name);
        userService.save(user);
    }

    /**
     * 指定id的数据
     * @param id
     * @return
     */
    @RequestMapping("get/{id}")
    public User get(@PathVariable("id") String id){
        User user = userService.getUser(id);
        return user;
    }

    /**
     *
     * @param user
     */
    @RequestMapping("/updateUser")
    public void updateUser(User user){
        userService.updateByPrimaryKey(user);
    }

    /**
     *
     * @param id
     */
    @RequestMapping("/delete/{id}")
    public void delete(@PathVariable("id") String id){
        userService.deleteByPrimaryKey(id);
    }
}

3.4 Main switch DemoApplication

 

 

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan("com.example.dao")
@EnableCaching
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

}


We generally write sql to the xml configuration file based on mybatis. Now let's add the mapping 

 


3.5 Create the corresponding mapper mapping
 

<?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.example.dao.UserDao">
  <resultMap id="BaseResultMap" type="com.example.entity.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, age
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from test_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from test_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.entity.User">
    insert into test_user (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.entity.User">
    insert into test_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.entity.User">
    update test_user
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.entity.User">
    update test_user
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

3.6 Focus on the key points, don't run the project. Need to configure application.properties

 

#mybatis
spring.datasource.url=jdbc:mysql://10.100.50.23/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=round&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis.config-location=classpath:mybatis-config.xml
mybatis.typeAliasesPackage=com.example.entity
mybatis.mapper-locations=classpath:mapper/**/*.xml


So far, the springboot+maven+mybatis project has been successfully built

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324129246&siteId=291194637