spring boot 整合jdbc和事务

       访问效果

         springboot连接数据库需要整合jdbc与事务,那么改怎么处理,答案是不需要我们处理,springboot已经实现,我们只需在pom文件中引入对应的库然后简单配置即可实现。jdbc驱动的引入,别忘了还有mybatis引入。下面我们来实现下:

1、j在pom文件中引入dbc驱动与mybatis

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
        
            mysql
            mysql-connector-java
            5.1.46
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        

 2、数据库连接池参数配置

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

3、mybatis配置

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

4、application配置

在启动类上添加扫描包注解(推荐): import tk.mybatis.spring.annotation.MapperScan;别导错包。
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、通用mapper配置

        通用Mapper的作者也为自己的插件编写了启动器,我们直接引入即可。在项目的 pom.xml 文件中加入如下依赖,注意:一旦引入了通用Mapper的启动器,会覆盖Mybatis官方启动器的功能,因此需要移除对官方Mybatis启动器的依赖。

     
        
            tk.mybatis
            mapper-spring-boot-starter
            2.1.5
        

6、编写UserMapper

package springbootdemo.mapper;

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

public interface UserMapper extends Mapper {
}

7、user表(需要自行去mysql创建数据库表新增用户数据,sql语句见下一步)

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信息


-- ----------------------------
-- 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、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、测试结果

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、测试输出结果

浏览器输入地址: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]

你可能感兴趣的:(后端java,spring,boot,java,spring)