代码改变世界

SpringBoot +MyBatis

2018-06-08 17:45  那么像你  阅读(70)  评论(0)    收藏  举报

1.maven 添加引用库, 在pom.xml中增加

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

mysql 数据库根据 不同的数据库引用不同的库

2.在application.properties中配置数据源及mybatis配置:application.properties 在resources目录下

#mybatis.config-location=classpath:mybatis-config.xml
#mybatis mapper文件的位置,mybatis xml的地址,在resources下查找
mybatis.mapper-locations=classpath*:mapper/*.xml
#扫描pojo类的位置,在此处指明扫描实体类的包,在mapper中就可以不用写pojo类的全路径名了 Model类的地址
mybatis.type-aliases-package=com.example.study

jdbc.type=mysql
spring.datasource.url=jdbc:mysql://172.21.100.111:3306/uPlatform?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.username=eg
spring.datasource.password=123456ABcd.6
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

注意 

mybatis.mapper-locations=classpath*:mapper/*.xml              是MyBatis mysql语句的xml的搜索地址
mybatis.type-aliases-package=com.example.study                是Model的搜索包

3.数据库新建表和插入数据

4.新建model和Dao接口

package com.example.study.Model;



public class User {
    private long  id;
    private String name;
    private String sex;
    private  int age;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

    public long getId() {
        return id;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

}
package com.example.study.Dao;

import com.example.study.Model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper//加上该注解才能使用@MapperScan扫描到
public interface UserDao {

    User getUserById(@Param("id") int id);

    int updateUser(@Param("user") User user);

    int insertUser(@Param("user") User user);

    int deleteUserById(@Param("id") int id);
}

5.新建mapper.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.example.study.Dao.UserDao">

    <select id="getUserById" resultType="User">
        SELECT
        id,
        name,
        sex,
        age
        FROM user
        WHERE ID = #{id}
    </select>
    <update id="updateUser">
        UPDATE user
        SET name = #{user.name},
        SEX = #{user.sex},
        AGE = #{user.age}
        WHERE id = #{user.id}
    </update>
    <insert id="insertUser" parameterType="com.example.study.Model.User" useGeneratedKeys="true" keyProperty="user.id">
        INSERT INTO
        user( name, sex, age)
        VALUES (
        #{user.name},
        #{user.sex},
        #{user.age}
        );
        INSERT INTO
        userlog(userid,context)
        VALUES(
        LAST_INSERT_ID(),
        'add'
        )
    </insert>
    <delete id="deleteUserById">
        DELETE user WHERE ID = #{id}
    </delete>

</mapper>
namespace="com.example.study.Dao.UserDao" 是指对应的Dao

6.为启动类添加注解

@ComponentScan("com.example.study")
@MapperScan("com.example.study") // 这个为扫描的Dao

7.写Controller

package com.example.study.Controller;

import com.example.study.Dao.UserDao;
import com.example.study.Dao.UserfAnnotationDao;
import com.example.study.Model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserfAnnotationDao userADao;

    @RequestMapping("/hello")
    public User hello(){
        User user = userDao.getUserById(1);
        System.out.println(user);
        return user;
    }
    @RequestMapping("/adduser")
    public String  adduser(String name,int age,String sex)
    {
        User u=new User();
        u.setName(name);
        u.setAge(age);
        u.setSex(sex);
      int returnid=   userDao.insertUser(u);
        return   Long.toString( u.getId()) +"   reid:"+ String.valueOf( returnid);
    }
}

8.运行即可测试

注意

1.扫描地址和配置文件

 

 

以上为xml模式,以下为注解模式

注解模式不需要xml,其他都一致,不过在Dao接口中用注解的方式书写sql语句

package com.example.study.Dao;

import com.example.study.Model.User;
import org.apache.ibatis.annotations.*;

import javax.jws.soap.SOAPBinding;
import java.util.List;

@Mapper
public interface UserfAnnotationDao {
    @Select("SELECT * FROM user WHERE id=#{id}")
    @Results(
            {
                    @Result(property = "id", column = "id"),
                    @Result(property = "name", column = "name"),
                    @Result(property = "sex", column = "sex"),
                    @Result(property = "age", column = "age")
            })
    User getUserById(int id);

    @Select("SELECT * FROM user")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "sex", column = "sex"),
            @Result(property = "age", column = "age")
    })
    List<User> queryAll();

    @Update("UPDATE user set name=#{user.name},sex=#{user.sex},age=#{user.age} where id=#{user.id}")
    int updateUser(User user);

    @Insert("INSERT INTO user(id.name,sex,age) Values(#{user.id},#{user.name},#{user.sex},#{user.age})")
    int insertUser(User user);

    @Delete("DELETE from user WHERE id=#{id}")
    int deleteUserById(int id);
}

使用注解自后就不需要mapper文件了,分别测试这几个方法均能正确执行,使用注解和使用xml的方式都差不多,通常情况下,如果没有复杂的连接查询,我们可以使用注解的方式,当设计到复杂的sql还是使用xml的方式更好掌控一些,所以通常情况下两种方式都会使用,根据sql的复杂程度选择不同的方式来提高开发效率。

 

下一篇文章,学习mybatis generator , mybatis generator工具来帮我们自动创建pojo类、mapper文件以及dao类并且会帮我们配置好它们的依赖关系,而我们只需要关系我们的业务逻辑直接使用就行了