springboot学习--springboot+maven+mybatis项目搭建

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_41669919/article/details/79159249

今天我们来搭建一个简单的基于springboot+mybatis+maven的项目,使用的数据库为mysql。

最终项目目录结构

一、项目创建

1.新建spring项目

选择Spring Initializr,选择jdk版本,之后点击Next

填写Group,Artifact,Type选择Maven Project 点击Next

添加项目依赖,暂时只需添加Web,Mybatis,Mysql三个依赖,点击Next

选择项目路径,点击Finish,创建成功

之后在application.properties资源文件中添加mybatis配置信息,项目启动时会自动加载配置项

#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.目录结构简单介绍

 2.1 java

这个就不用多说了。放我们写的java文件的

2.2 resources

springboot主张无xml配置,但是还是需要一些最基础的信息配置的,例如sql账号密码的设置,在简洁你的账号密码还是需要你自己配置滴,它是没办法帮你自动生成的。所以一般配置文件都是放到resources下的。具体默认生成的文件都是做什么的以及什么资源放到什么文件下可以看我之前写过的一片关于各文件夹作用的文章springboot目录结构详解

2.3 开关文件

DemoApplication文件就是springboot的核心开关了。

3.整合

需求:从数据库中查询出某一用户的所有信息返回给前台页面

好了,上面做了简单的声明。开始整合。还是基于开发的最基本的三层架架构进行开发

数据库如下 


3.1 User(创建一个来接收查询出来数据的对象)

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层创建接口

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接口及实现类

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层

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 主开关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);
   }

}


我们一般基于mybatis都是将sql写到xml配置文件中。现在我们来添加映射 


3.5 创建对应的mapper映射
 

<?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 重点重点,不要跑项目。需要配置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


至此,springboot+maven+mybatis项目搭建成功

猜你喜欢

转载自blog.csdn.net/baidu_41669919/article/details/79159249