SpringBoot(9) SpringBoot整合Mybaties

一、近几年常用的访问数据库的方式和优缺点
1、原始java访问数据库
  开发流程麻烦
  <1>注册驱动/加载驱动
    Class.forName("com.mysql.jdbc.Driver")
  <2>建立连接
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");
  <3>创建Statement
  <4>执行SQL语句
  <5>处理结果集
  <6>关闭连接,释放资源
2、apache dbutils框架
  比上一步简单点
  官网:https://commons.apache.org/proper/commons-dbutils/
3、jpa框架
  spring-data-jpa
  jpa在复杂查询的时候性能不是很好
4、Hiberante 解释:ORM:对象关系映射Object Relational Mapping
  企业大都喜欢使用hibernate
5、Mybatis框架
  互联网行业通常使用mybatis
  不提供对象和关系模型的直接映射,半ORM

二、Mybatis准备

1、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter

2、加入依赖(可以用 http://start.spring.io/ 下载)

 1    <!-- 引入starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
<scope>runtime</scope>
</dependency> <!-- MySQL的JDBC驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入第三方数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

3、在application.properties文件中加入

 #可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =password #使用阿里巴巴druid数据源,默认使用自带的
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource #开启控制台打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

注: <1>driver-class-name不需要加入,可以自动识别

   <2>数据库连接池可以用自带的 com.zaxxer.hikari.HikariDataSource

   <3>加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成

4、启动类增加mapper扫描

@MapperScan("net.xdclass.base_project.mapper")

技巧:保存对象,获取数据库自增id

@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")

注:开发mapper,参考语法 http://www.mybatis.org/mybatis-3/zh/java-api.html

5、相关资料:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples

整合问题集合:
https://my.oschina.net/hxflar1314520/blog/1800035

https://blog.csdn.net/tingxuetage/article/details/80179772

6.代码演示

项目结构

SpringBoot(9) SpringBoot整合Mybaties

启动类

 @SpringBootApplication //一个注解顶下面3个
@MapperScan("net.xdclass.base_project.mapper")
public class XdclassApplication { public static void main(String[] args) throws Exception {
SpringApplication.run(XdclassApplication.class, args);
} }

Mapper层的UserMapper

 public interface UserMapper {

     //推荐使用#{}取值,不要用${},因为存在注入的风险
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(User user); /**
* 功能描述:查找全部
* @return
*/
@Select("SELECT * FROM user")
@Results({
@Result(column = "create_time",property = "createTime"),
@Result(column = "create_time",property = "createTime")
//javaType = java.util.Date.class
})
List<User> getAll(); /**
* 功能描述:根据id找对象
* @param id
* @return
*/
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(column = "create_time",property = "createTime")
})
User findById(Long id); /**
* 功能描述:更新对象
* @param user
*/
@Update("UPDATE user SET name=#{name} WHERE id =#{id}")
void update(User user); /**
* 功能描述:根据id删除用户
* @param userId
*/
@Delete("DELETE FROM user WHERE id =#{userId}")
void delete(Long userId); }

注:在查找中@Result表示:从表中的column映射到user类中的property。如果有多个用逗号分隔。

Service层的UserService

 public interface UserService {

     public int add(User user);

 }

ServiceImpl层的UserServiceImpl

 @Service
public class UserServiceImpl implements UserService{ @Autowired
private UserMapper userMapper; @Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
} }

Controller层的UserController

 @RestController
@RequestMapping("/api/v1/user")
public class UserController { @Autowired
private UserService userService; @Autowired
private UserMapper userMapper; /**
* 功能描述: user 保存接口
* @return
*/
@GetMapping("add")
public Object add(){ User user = new User();
user.setAge(11);
user.setCreateTime(new Date());
user.setName("xdclass");
user.setPhone("10010000");
int id = userService.add(user); return JsonData.buildSuccess(id);
} /**
* 功能描述:查找全部用户
* @return
*/
@GetMapping("findAll")
public Object findAll(){ return JsonData.buildSuccess(userMapper.getAll());
} @GetMapping("find_by_id")
public Object findById(long id){
return JsonData.buildSuccess(userMapper.findById(id));
} @GetMapping("del_by_id")
public Object delById(long id){
userMapper.delete(id);
return JsonData.buildSuccess();
} @GetMapping("update")
public Object update(String name,int id){
User user = new User();
user.setName(name);
user.setId(id);
userMapper.update(user);
return JsonData.buildSuccess();
} }
上一篇:docker pureftpd


下一篇:微信小程序 --- loading提示框