1.jdbc

步骤:

1)使用idea创建一个springboot项目

创建过程中,要选择依赖模块 thymeleaf和web和jdbc

springboot activity h2持久化 springboot持久层框架选择_bc


springboot activity h2持久化 springboot持久层框架选择_spring_02


springboot activity h2持久化 springboot持久层框架选择_spring_03


这样做 pom.xml中就有thymeleaf和web和jdbc依赖,不用自己添加。

2)pom.xml增加 mysql连接器依赖,数据源依赖(用的是阿里的数据源,不是springboot自带的数据源,可以选择数据源)

<!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--数据源 保存配置信息(外存)的对象(内存)-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

3)增加配置文件,保存java连接数据库需要的信息
地址
驱动
用户名
密码
jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true &characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123
jdbc.driverClassName=com.mysql.jdbc.Driver

3)增加配置文件对应的java类,框架启动通过框架提供的注解将配置文件信息解析到java对象中
@PropertySource(“classpath:/jdbc.properties”)注解:将双人床、

package com.bjsxt.springbootjdbc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:/jdbc.properties")
public class JdbcConfiguration {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }
}

4)其他类引入,比如这样一个Controller里面自动注入DataSource,在他的方法里面就可以使用数据源对象了。

package com.bjsxt.springbootjdbc.controller;

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

import javax.sql.DataSource;

@Controller
public class PageController {
    @Autowired
    private DataSource dataSource;

    @RequestMapping("/showInfo")
    public void showInfo(){
        System.out.println("dataSource");
    }
}

运行结果:

debug模式,可看见,配置文件信息加载到对象里面了

页面没有设置,不用管

springboot activity h2持久化 springboot持久层框架选择_Source_04


springboot activity h2持久化 springboot持久层框架选择_spring_05


补充:

jdbc配置文件转对象属性的方式

方式一:@PropertySource(配置文件路径),@Value("springboot activity h2持久化 springboot持久层框架选择_bc_06{配置文件中的键}")指明对应的文件键的值,传递进下面属性中。

这个配置文件可以是任意名称的。

方式二:@ConfigurationProperties(prefix = “jdbc”),@EnableConfigurationProperties(JdbcProperties.class)
使用 org.springframework.boot.context.properties.ConfigurationProperties 注解,加载application.properties文件中的属性到加了这个注解的对象中,通过set方法设置值,所以类中的属性名称要与表中的一样。在获取数据源的配置类前面增加@EnableConfigurationProperties(JdbcProperties.class)引进来配置信息对象。
a 写@Autowired 注入
b 写构造方法注入
c 方法中的形参中注入

一个配置信息类,properties变成java对象

package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

一个配置类获取数据源。需要导入配置信息。

package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
//@PropertySource("classpath:/jdbc.properties")
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
    /*@Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;*/

    /*@Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource =new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setPassword(password);
        dataSource.setUsername(username);
        dataSource.setUrl(url);
        return dataSource;
    }*/
    /**
     * 方式一,通过注解注入配置信息
     * @Autowired
     *     JdbcProperties jdbcProperties;
     */

    /**
     * 方式二:通过构造方法赋值
     * JdbcProperties jdbcProperties;
     *     JdbcConfiguration(JdbcProperties jdbcProperties){
     *         this.jdbcProperties=jdbcProperties;
     *     }
     */
    /**
     * 方式三:通过方法形参赋值
     * @param jdbcProperties
     * @return
     */
    @Bean
    public DataSource getDataSource(JdbcProperties jdbcProperties){
        DruidDataSource dataSource =new DruidDataSource();
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setPassword(jdbcProperties.getPassword());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setUrl(jdbcProperties.getUrl());
        return dataSource;
    }
}

运行结果:

连接本机test数据库,实现查询所有接口:

springboot activity h2持久化 springboot持久层框架选择_spring_07


2.mybatis

步骤:

1)创建一个springboot项目,选择web依赖,thymeleaf依赖,jdbc 依赖,mybatis依赖。这相当于在pom.xml中自动写了dependency,web启动器的dependency,thymeleaf启动器,jdbc启动器,和mybatis启动器。

2)增加 数据库驱动,数据源实现类依赖(因为java整合数据库要加数据源和驱动依赖)

<!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- 数据源实现类 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

3)增加 mybatise-generator-maven-plugin插件(springboot会根据表生成映射的类和持久层的接口,映射配置文件)
既然要连接表,就要有数据库驱动依赖,这样才能运行。否则报错。
generatorConfig.xml直接复制过来,修改连接数据库用户名,数据库名称,密码,生成哪张表的模型类和持久层接口和文件,生成的模型类放在哪个包里面,生成的持久层接口放在哪个包里。

<plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <configurationFile>${project.basedir/src/main/resources/generatorConfig.xml}</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>

generatorConfig.xml

<?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>
	<context id="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
			password="123">
		</jdbcConnection>
		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
			NUMERIC 类型解析为java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成PO类的位置 -->
		<javaModelGenerator targetPackage="com.bjsxt.springbootmybatise.pojo"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
		<sqlMapGenerator targetPackage="com.bjsxt.springbootmybatise.mapper"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper接口生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.bjsxt.springbootmybatise.mapper"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定数据库表 -->
		<table schema="" tableName="users"></table>
	</context>
</generatorConfiguration>

4)在idea右侧运行插件generator,生成对应的Users.java,UsersExample.java,UsersMapper(接口),UsersMapper.xml

springboot activity h2持久化 springboot持久层框架选择_Source_08


springboot activity h2持久化 springboot持久层框架选择_Source_09


5)在启动类前面加注解@MapperScan(“com.bjsxt.springbootmybatise.mapper”)

这个注解会扫描mapper接口,如果配置文件也在这里面,就会根据这个生成一个实现类。类似过去写的UsersDaoImpl.

如果xml不在mapper包下面,需要在application.yml中配置

如果写了type-aliases-package,那么UsesMapper.xml中的ResultMap的type就不用写包名称

mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.bjsxt.springbootmybatis.pojo

注意1:

dtd约束文件如果报红,那么需要配置一下路径

springboot activity h2持久化 springboot持久层框架选择_Source_10


springboot activity h2持久化 springboot持久层框架选择_spring_11


修改后:

springboot activity h2持久化 springboot持久层框架选择_spring_12

注意2:

预更新的页面中需要增加id,否则更新时,id是null,导致更新失败

springboot activity h2持久化 springboot持久层框架选择_spring_13


注意3:

项目结构中是src/main/resources,resources有一个s。在pom.xml中写生成器配置文件时需要写上正确的包名称。少写一个s启动会报错。

springboot activity h2持久化 springboot持久层框架选择_spring_14


源码:

启动类

package com.bjsxt.springbootmybatise;

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

@SpringBootApplication
@MapperScan("com.bjsxt.springbootmybatise.mapper")
public class SpringbootmybatiseApplication {

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

}

pojo

package com.bjsxt.springbootmybatise.pojo;

public class Users {
    private Integer id;

    private String name;

    private String sex;

    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
         = name == null ? null : name.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
package com.bjsxt.springbootmybatise.pojo;

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

public class UsersExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public UsersExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andIdIsNull() {
            addCriterion("id is null");
            return (Criteria) this;
        }

        public Criteria andIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria) this;
        }

        public Criteria andIdEqualTo(Integer value) {
            addCriterion("id =", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotEqualTo(Integer value) {
            addCriterion("id <>", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThan(Integer value) {
            addCriterion("id >", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThan(Integer value) {
            addCriterion("id <", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdIn(List<Integer> values) {
            addCriterion("id in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotIn(List<Integer> values) {
            addCriterion("id not in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion("id between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion("id not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andNameIsNull() {
            addCriterion("name is null");
            return (Criteria) this;
        }

        public Criteria andNameIsNotNull() {
            addCriterion("name is not null");
            return (Criteria) this;
        }

        public Criteria andNameEqualTo(String value) {
            addCriterion("name =", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotEqualTo(String value) {
            addCriterion("name <>", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThan(String value) {
            addCriterion("name >", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThanOrEqualTo(String value) {
            addCriterion("name >=", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThan(String value) {
            addCriterion("name <", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThanOrEqualTo(String value) {
            addCriterion("name <=", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLike(String value) {
            addCriterion("name like", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotLike(String value) {
            addCriterion("name not like", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameIn(List<String> values) {
            addCriterion("name in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotIn(List<String> values) {
            addCriterion("name not in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameBetween(String value1, String value2) {
            addCriterion("name between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotBetween(String value1, String value2) {
            addCriterion("name not between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andSexIsNull() {
            addCriterion("sex is null");
            return (Criteria) this;
        }

        public Criteria andSexIsNotNull() {
            addCriterion("sex is not null");
            return (Criteria) this;
        }

        public Criteria andSexEqualTo(String value) {
            addCriterion("sex =", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotEqualTo(String value) {
            addCriterion("sex <>", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexGreaterThan(String value) {
            addCriterion("sex >", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexGreaterThanOrEqualTo(String value) {
            addCriterion("sex >=", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexLessThan(String value) {
            addCriterion("sex <", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexLessThanOrEqualTo(String value) {
            addCriterion("sex <=", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexLike(String value) {
            addCriterion("sex like", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotLike(String value) {
            addCriterion("sex not like", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexIn(List<String> values) {
            addCriterion("sex in", values, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotIn(List<String> values) {
            addCriterion("sex not in", values, "sex");
            return (Criteria) this;
        }

        public Criteria andSexBetween(String value1, String value2) {
            addCriterion("sex between", value1, value2, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotBetween(String value1, String value2) {
            addCriterion("sex not between", value1, value2, "sex");
            return (Criteria) this;
        }

        public Criteria andAgeIsNull() {
            addCriterion("age is null");
            return (Criteria) this;
        }

        public Criteria andAgeIsNotNull() {
            addCriterion("age is not null");
            return (Criteria) this;
        }

        public Criteria andAgeEqualTo(Integer value) {
            addCriterion("age =", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeNotEqualTo(Integer value) {
            addCriterion("age <>", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeGreaterThan(Integer value) {
            addCriterion("age >", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeGreaterThanOrEqualTo(Integer value) {
            addCriterion("age >=", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeLessThan(Integer value) {
            addCriterion("age <", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeLessThanOrEqualTo(Integer value) {
            addCriterion("age <=", value, "age");
            return (Criteria) this;
        }

        public Criteria andAgeIn(List<Integer> values) {
            addCriterion("age in", values, "age");
            return (Criteria) this;
        }

        public Criteria andAgeNotIn(List<Integer> values) {
            addCriterion("age not in", values, "age");
            return (Criteria) this;
        }

        public Criteria andAgeBetween(Integer value1, Integer value2) {
            addCriterion("age between", value1, value2, "age");
            return (Criteria) this;
        }

        public Criteria andAgeNotBetween(Integer value1, Integer value2) {
            addCriterion("age not between", value1, value2, "age");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

mapper

package com.bjsxt.springbootmybatise.mapper;

import com.bjsxt.springbootmybatise.pojo.Users;
import com.bjsxt.springbootmybatise.pojo.UsersExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UsersMapper {
    long countByExample(UsersExample example);

    int deleteByExample(UsersExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Users record);

    int insertSelective(Users record);

    List<Users> selectByExample(UsersExample example);

    Users selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Users record, @Param("example") UsersExample example);

    int updateByExample(@Param("record") Users record, @Param("example") UsersExample example);

    int updateByPrimaryKeySelective(Users record);

    int updateByPrimaryKey(Users record);
}
<?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.bjsxt.springbootmybatise.mapper.UsersMapper">
  <resultMap id="BaseResultMap" type="com.bjsxt.springbootmybatise.pojo.Users">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    id, name, sex, age
  </sql>
  <select id="selectByExample" parameterType="com.bjsxt.springbootmybatise.pojo.UsersExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from users
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from users
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.bjsxt.springbootmybatise.pojo.UsersExample">
    delete from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.bjsxt.springbootmybatise.pojo.Users">
    insert into users (id, name, sex, 
      age)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.bjsxt.springbootmybatise.pojo.Users">
    insert into users
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="sex != null">
        sex,
      </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="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.bjsxt.springbootmybatise.pojo.UsersExample" resultType="java.lang.Long">
    select count(*) from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update users
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test=" != null">
        name = #{,jdbcType=VARCHAR},
      </if>
      <if test="record.sex != null">
        sex = #{record.sex,jdbcType=VARCHAR},
      </if>
      <if test="record.age != null">
        age = #{record.age,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update users
    set id = #{record.id,jdbcType=INTEGER},
      name = #{,jdbcType=VARCHAR},
      sex = #{record.sex,jdbcType=VARCHAR},
      age = #{record.age,jdbcType=INTEGER}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.bjsxt.springbootmybatise.pojo.Users">
    update users
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.bjsxt.springbootmybatise.pojo.Users">
    update users
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

controller

package com.bjsxt.springbootmybatise.controller;

import com.bjsxt.springbootmybatise.pojo.Users;
import com.bjsxt.springbootmybatise.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UsersController {
    @Autowired
    UsersService usersService;
    @RequestMapping("/queryAllUsers")
    public String queryAllUsers(Model model){
        List<Users> list=usersService.queryAllUsers();
        model.addAttribute("list",list);
        return "userList";
    }
    @RequestMapping("/addUser")
    public String addUser(Users users){
        int result=usersService.addUser(users);
        return "ok";
    }
    @RequestMapping("/preUpdate/{id}")
    public String preUpdate(@PathVariable String id,Model model){
        Users users=usersService.queryUser(Integer.valueOf(id));
        model.addAttribute("user",users);
        return "preUpdate";
    }
    @RequestMapping("/updateUser")
    public String updateUser(Users users){
        int result=usersService.updateUser(users);
        return "ok";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id,Model model){
        int result=usersService.delete(Integer.valueOf(id));
        return "ok";
    }
}
package com.bjsxt.springbootmybatise.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/page")
public class PageController {
    @RequestMapping("/{page}")
    public String getPage(@PathVariable String page){
        return page;
    }
}

service

package com.bjsxt.springbootmybatise.service;

import com.bjsxt.springbootmybatise.pojo.Users;

import java.util.List;

public interface UsersService {
    List<Users> queryAllUsers();

    int addUser(Users users);

    Users queryUser(Integer id);

    int updateUser(Users users);

    int delete(Integer id);
}
package com.bjsxt.springbootmybatise.service;

import com.bjsxt.springbootmybatise.mapper.UsersMapper;
import com.bjsxt.springbootmybatise.pojo.Users;
import com.bjsxt.springbootmybatise.pojo.UsersExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    UsersMapper usersMapper;
    @Override
    public List<Users> queryAllUsers() {
        return usersMapper.selectByExample(new UsersExample());
    }

    @Override
    @Transactional
    public int addUser(Users users) {
        return usersMapper.insert(users);
    }

    @Override
    public Users queryUser(Integer id) {
        return usersMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int updateUser(Users users) {
        return usersMapper.updateByPrimaryKey(users);
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        return usersMapper.deleteByPrimaryKey(id);
    }
}

CREATE TABLE `users` (
  `id` int(16) NOT NULL AUTO_INCREMENT,
  `name` varchar(256) NOT NULL,
  `sex` varchar(16) NOT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

springboot activity h2持久化 springboot持久层框架选择_Source_15


userList.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head >
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
<table border="1px">
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>操作1</th>
        <th>操作2</th>
    </tr>
    <tr th:each="u : ${list}">
        <td th:text="${u.id}"></td>
        <td th:text="${}"></td>
        <td th:if="${u.sex=='0'}"><span th:text="女"></span></td>
        <td th:if="${u.sex=='1'}"><span th:text="男"></span></td>
        <td th:text="${u.age}"></td>
        <td><a th:href="@{/user/preUpdate/{id}(id=${u.id})}">更新</a></td>
        <td><a th:href="@{/user/delete/{id}(id=${u.id})}">删除</a></td>
    </tr>
</table>
<a th:href="@{/page/addUser}">新增用户</a>
</body>
</html>

addUser.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>新增用户</title>
</head>
<body>
<form action="/user/addUser" method="post">
    姓名:<input name="name" value="请输入姓名..." type="text"><br>
    性别:女<input name="sex" type="radio" value="0">
          男<input name="sex" type="radio" value="1"><br>
    年龄:<input name="age" value="请输入年龄..." type="text"><br>
    <input type="submit" value="点击新增">
</form>
</body>
</html>

preUpdate.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>更新用户</title>
</head>
<body>
<form action="/user/updateUser" method="post">
    <input name="id" th:value="${user.id}" type="hidden"><br>
    姓名:<input name="name" th:value="${}" type="text"><br>
    性别:
    <span th:if="${user.sex=='0'}">
    女<input name="sex" type="radio" value="0" th:checked="true">
    男<input name="sex" type="radio" value="1"><br>
    </span>

    <span th:if="${user.sex=='1'}">
    女<input name="sex" type="radio" value="0">
    男<input name="sex" type="radio" value="1" th:checked="true"><br>
    </span>

    年龄:<input name="age" th:value="${user.age}" type="text"><br>
    <input type="submit" value="点击更新">
</form>
</body>
</body>
</html>

ok.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>操作成功</title>
</head>
<body>
操作成功!
<a th:href="@{/user/queryAllUsers}">点击查看所有用户</a>
</body>
</html>

运行结果:

查所有:

springboot activity h2持久化 springboot持久层框架选择_Source_16

增加:

springboot activity h2持久化 springboot持久层框架选择_spring_17


springboot activity h2持久化 springboot持久层框架选择_bc_18


springboot activity h2持久化 springboot持久层框架选择_bc_19

预更新:

springboot activity h2持久化 springboot持久层框架选择_Source_20

更新:

springboot activity h2持久化 springboot持久层框架选择_Source_21


springboot activity h2持久化 springboot持久层框架选择_bc_22


springboot activity h2持久化 springboot持久层框架选择_Source_23

删除:

springboot activity h2持久化 springboot持久层框架选择_bc_24


springboot activity h2持久化 springboot持久层框架选择_spring_25


springboot activity h2持久化 springboot持久层框架选择_spring_26