spring boot方式整合mybatis

本文记录两种整合方式,两种都是spring boot方式整合。xml或注解版Generator自动生成版

第一种:

(xml或注解版)
整体全家福如下,可以照着全家福来创建类与xm文件
在这里插入图片描述

第1步:导入pom文件依赖

 <dependencies>
        <!-- 自动get set constructor -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
<!--        mybatis要依赖的包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
<!--        jdbc链接包,必备-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--        mysql包,必备-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <scope>runtime</scope>
                        <version>8.0.18</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

第2步:编写配置文件(application.properties)

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
//下面的student是数据库名
spring.datasource.url=jdbc:mysql://localhost:3306/student?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=lcy123456
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5


#mybatis
#自动生成语句
#mybatis-generator:mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate
mybatis.configuration.map-underscore-to-camel-case=true
#绑定实体类
mybatis.type-aliases-package=com.mybatis.integration_mybatis.pojo.Student
mybatis.mapper-locations=classpath:mapper/*.xml

第3步:创建一个实体类(Student.java)
@data需要引用lombok插件,加了@data相当于自动生成了get/set方法

@Data
public class Student {
    public int Id;
    public String username;
}

第3步:编写mapper的接口与xml(StudentMapper.java与StudentMapper.xml)
注意两个注解一定不能少@Mapper与@Repository
接口的方法名称对应xml的id,并且接口名与xml的名字要一致

/**
 * @author mybatis接口
 */
@Mapper
@Repository
public interface StudentMapper {
    //通过名字插入一条信息
    int insert(String username);

    //通过id删除一条信息
    int delete(int id);

    //通过id与名字修改一条信息
    int edit(Student student);

    //查询所有信息
    List<Student> getAll();
}

<?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">
<!--namespace对应接口所在类-->
<mapper namespace="com.mybatis.integration_mybatis.mapper.StudentMapper">
<!--    将实体类作为返回值-->
    <resultMap id="StudentMap" type="com.mybatis.integration_mybatis.pojo.Student">
        <result property="username" column="username"/>
    </resultMap>
<!--    resultMap是返回类型-->
    <select id="getAll" resultMap="StudentMap">
       select * from student
    </select>
<!--   parameterType是参数类型 -->
    <insert id="insert" parameterType="com.mybatis.integration_mybatis.pojo.Student">
        insert into student(username) values(#{username})
    </insert>
    <delete id="delete" parameterType="int">
        delete from student where Id=#{id}
    </delete>
    <update id="edit" parameterType="com.mybatis.integration_mybatis.pojo.Student">
        update student set username=#{username} where Id=#{id}
    </update>
</mapper>

第4步:编写controller(StudentController.java)
有4个方法,增删改查

@Controller
public class StudentController {
    @Autowired
    private StudentMapper studentMapper;

    @RequestMapping("/all")
    @ResponseBody
    public List<Student> getAll(){
        return studentMapper.getAll();
    }

    @RequestMapping("/add/{username}")
    @ResponseBody
    public int add(@PathVariable("username") String username){
        return studentMapper.insert(username);
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public int delete(@PathVariable("id") int id){
        return studentMapper.delete(id);
    }

    @RequestMapping("/edit/{id}/{username}")
    @ResponseBody
    public int edit(@PathVariable("id") int id,
                    @PathVariable("username") String username) {
        Student student = new Student();
        student.setId(id);
        student.setUsername(username);
        return studentMapper.edit(student);
    }
}

第5步:主程序加注释然后测试

@SpringBootApplication
//映射mapper接口
@MapperScan(basePackages = "com.mybatis.integration_mybatis.mapper")
public class IntegrationMybatisApplication {

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

}

先在数据库加入几行信息
查询所有信息:http://localhost:8080/all
添加一条信息:http://localhost:8080/add/“要添加的名字(自己写)”
修改一条信息: http://localhost:8080/edit/数据库的id号/要修改的名字
删除一条信息: http://localhost:8080/delete/要删除的数据库id号

第二种

Generator自动生成版
全家福如下,类虽然看着多,但是大多不需要写
在这里插入图片描述
第1步和第2步与第一种一样。
第3步:在resources下创建generatorConfig.xml

此xml可以根据数据库的表名自动生成POJO类与mapper语句

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <classPathEntry  location="mysql-connector-java-8.0.18.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/student?serverTimezone=UTC"
                        userId="root"
                        password="lcy123456">
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--targetPackage实体类的存放位置-->
        <javaModelGenerator targetPackage="com.mybatis.integration_mybatis.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--targetPackage,mapper的xml映射位置-->
        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!--targetPackage,mapper的xml存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis.integration_mybatis.mapper"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

<!--        数据库对应的实体类-->
        <table tableName="student" domainObjectName="Student" >
        </table>
        <table tableName="book" domainObjectName="Book" >
        </table>

    </context>
</generatorConfiguration>

第4步:编写controller

@Controller
public class StudentController {

    @Autowired
    private BookMapper bookMapper;

    @ResponseBody
    @RequestMapping("/allbook")
    public List<Book> Allbook(){
        BookExample bookExample = new BookExample();
        List<Book> books = bookMapper.selectByExample(bookExample);
        return books;
    }
    @ResponseBody
    @RequestMapping("/delete/{name}")
    public int delete(@PathVariable("name")String name) {
        BookExample bookExample = new BookExample();
        bookExample.createCriteria()
                .andNameEqualTo(name);
        return bookMapper.deleteByExample(bookExample);
    }
    @ResponseBody
    @RequestMapping("/add/{name}")
    public int add(@PathVariable("name")String name) {
        Book book = new Book();
        book.setName(name);
        return bookMapper.insert(book);
    }
    @ResponseBody
    @RequestMapping("/edit/{id}/{name}")
    public int delete(@PathVariable("name")String name,
                      @PathVariable("id")int id) {
        Book book = new Book();
        book.setId(id);
        book.setName(name);
        return bookMapper.updateByPrimaryKey(book);
    }

第5步:主程序加注释然后测试

@SpringBootApplication
//映射mapper接口
@MapperScan(basePackages = "com.mybatis.integration_mybatis.mapper")
public class IntegrationMybatisApplication {

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

}

先在数据库加入几行信息
查询所有信息:http://localhost:8080/allbook
添加一条信息:http://localhost:8080/add/“要添加的名字(自己写)”
修改一条信息: http://localhost:8080/edit/数据库的id号/要修改的名字
删除一条信息: http://localhost:8080/delete/要删除的数据库id号

发布了17 篇原创文章 · 获赞 0 · 访问量 469
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览