Spring boot integrates jdbc and transactions

       access effect

         Springboot needs to integrate jdbc and transactions to connect to the database, so how to deal with it? The answer is that we don’t need to deal with it. Springboot has already been implemented. We only need to introduce the corresponding library in the pom file and then simply configure it. The introduction of the jdbc driver, don't forget the introduction of mybatis. Let's implement it below:

1. j introduces the dbc driver and mybatis in the pom file

        <!--jdbc事务-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- mysql 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

 2. Database connection pool parameter configuration

  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mumu
    username: "数据库账号"
    password: "数据库密码"

3. mybatis configuration

#mybatis
# mybatis配置
mybatis:
  # 实体类别名包路径
  type-aliases-package: springbootdemo.pojo
  # 映射文件路径
  # mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4. Application configuration

Add scanning package annotations to the startup class (recommended): import tk.mybatis.spring.annotation.MapperScan; do not import the wrong package.
package springbootdemo;

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

@SpringBootApplication
@MapperScan("springbootdemo.mapper")
public class Application {

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

}

5. General mapper configuration

        The author of the general Mapper also wrote a starter for his own plugin, we can import it directly. Add the following dependencies to the pom.xml file of the project. Note: Once the general Mapper launcher is introduced, the functions of the official Mybatis launcher will be overwritten, so the dependency on the official Mybatis launcher needs to be removed.

     <!-- 通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>

6. Write UserMapper

package springbootdemo.mapper;

import springbootdemo.pojo.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}

7. User table (you need to go to mysql to create a database table to add user data, see the next step for the sql statement)

package springbootdemo.pojo;

import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Data
@Table(name = "tb_user")
public class User{
    // id
    @Id
    //开启主键自动回填
    @KeySql(useGeneratedKeys = true)
    private Long id;
    // 用户名
    private String userName;
    // 密码
    private String password;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 性别,1男性,2女性
    private Integer sex;
    // 出生日期
    private Date birthday;
    // 创建时间
    private Date created;
    // 更新时间
    private Date updated;
    // 备注
    private String note;
}

8. SQL information


-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
  `password` varchar(100) DEFAULT NULL COMMENT '密码',
  `name` varchar(100) DEFAULT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL COMMENT '年龄',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别,1男性,2女性',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `note` varchar(255) DEFAULT NULL COMMENT '备注',
  `created` datetime DEFAULT NULL COMMENT '创建时间',
  `updated` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'sw', '123456', '千帆v', '30', '1', '1964-08-08', '李先生很棒', '2014-09-19 16:56:04', '2014-09-21 11:24:59');
INSERT INTO `tb_user` VALUES ('2', '34r', '123456', '李哇', '21', '2', '1995-01-01', '李李先生很棒', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('3', 'dsff', '123456', '王如何', '22', '2', '1994-01-01', '李先生很棒', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('4', 'ht', '123456', '张奥迪', '20', '1', '1996-09-01', '李先生很棒', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('5', 'grr', '123456', '李二', '28', '1', '1988-01-01', '李娜李先生很棒', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('6', 'rr', '123456', '李法人', '23', '1', '1993-08-08', '李雷李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('7', 'hh', '123456', '威威', '24', '2', '1992-08-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('8', 'hrr', '123456', '为如', '21', '2', '2008-07-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('9', 'kytt', '123456', '马搭', '18', '2', '2012-08-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('10', 'gvr', '123456', '安安', '45', '2', '1971-08-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('11', 'htrh', '123456', 'de', '33', '2', '1983-08-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('12', 'wre', '123456', '马大哈', '46', '2', '1980-08-08', '李先生很棒', '2014-09-20 11:41:15', '2014-09-20 11:41:15');

9. Writing UserService

package springbootdemo.UserService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import springbootdemo.mapper.UserMapper;
import springbootdemo.pojo.User;

@Service
public class UserService {

    @Autowired(required=false)
    private UserMapper userMapper;

    //根据id查询
    public User queryById(Long id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public void saveUser(User user) {
        System.out.println("新增用户...");
        userMapper.insertSelective(user);
    }
}

10. Test results

package springbootdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import springbootdemo.UserService.UserService;
import springbootdemo.pojo.User;

import javax.sql.DataSource;

@RestController
public class HelloController {


    @Autowired
    private UserService userService;
    /**
     * 根据id获取用户
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable Long id){
        return userService.queryById(id);
    }

}

11. Test output results

Browser input address: http://localhost:8080/user/6

SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e8af71] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@546085857 wrapping com.mysql.jdbc.JDBC4Connection@574e7689] will not be managed by Spring
==>  Preparing: SELECT id,user_name,password,name,age,sex,birthday,created,updated,note FROM tb_user WHERE id = ? 
==> Parameters: 6(Long)
<==    Columns: id, user_name, password, name, age, sex, birthday, created, updated, note
<==        Row: 6, lilei, 123456, 李雷, 23, 1, 1993-08-08, 2014-09-20 11:41:15.0, 2014-09-20 11:41:15.0, 李先生很棒
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e8af71]

Guess you like

Origin blog.csdn.net/shi450561200/article/details/131930932