一、近几年常用的访问数据库的方式和优缺点
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-->
2 <dependency>
3 <groupId>org.mybatis.spring.boot</groupId>
4 <artifactId>mybatis-spring-boot-starter</artifactId>
5 <version>1.3.2</version>
6 <scope>runtime</scope>
7 </dependency>
8
9 <!-- MySQL的JDBC驱动包 -->
10 <dependency>
11 <groupId>mysql</groupId>
12 <artifactId>mysql-connector-java</artifactId>
13 <scope>runtime</scope>
14 </dependency>
15 <!-- 引入第三方数据源 -->
16 <dependency>
17 <groupId>com.alibaba</groupId>
18 <artifactId>druid</artifactId>
19 <version>1.1.6</version>
20 </dependency>
3、在application.properties文件中加入
1 #可以自动识别
2 #spring.datasource.driver-class-name =com.mysql.jdbc.Driver
3
4 spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
5 spring.datasource.username =root
6 spring.datasource.password =password
7
8 #使用阿里巴巴druid数据源,默认使用自带的
9 spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
10
11 #开启控制台打印sql
12 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.代码演示
项目结构
启动类
1 @SpringBootApplication //一个注解顶下面3个
2 @MapperScan("net.xdclass.base_project.mapper")
3 public class XdclassApplication {
4
5 public static void main(String[] args) throws Exception {
6 SpringApplication.run(XdclassApplication.class, args);
7 }
8
9 }
Mapper层的UserMapper
1 public interface UserMapper {
2
3
4 //推荐使用#{}取值,不要用${},因为存在注入的风险
5 @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
6 @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
7 int insert(User user);
8
9
10
11 /**
12 * 功能描述:查找全部
13 * @return
14 */
15 @Select("SELECT * FROM user")
16 @Results({
17 @Result(column = "create_time",property = "createTime"),
18 @Result(column = "create_time",property = "createTime")
19 //javaType = java.util.Date.class
20 })
21 List<User> getAll();
22
23
24
25 /**
26 * 功能描述:根据id找对象
27 * @param id
28 * @return
29 */
30 @Select("SELECT * FROM user WHERE id = #{id}")
31 @Results({
32 @Result(column = "create_time",property = "createTime")
33 })
34 User findById(Long id);
35
36
37
38 /**
39 * 功能描述:更新对象
40 * @param user
41 */
42 @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
43 void update(User user);
44
45 /**
46 * 功能描述:根据id删除用户
47 * @param userId
48 */
49 @Delete("DELETE FROM user WHERE id =#{userId}")
50 void delete(Long userId);
51
52 }
注:在查找中@Result表示:从表中的column映射到user类中的property。如果有多个用逗号分隔。
Service层的UserService
1 public interface UserService {
2
3 public int add(User user);
4
5 }
ServiceImpl层的UserServiceImpl
1 @Service
2 public class UserServiceImpl implements UserService{
3
4 @Autowired
5 private UserMapper userMapper;
6
7 @Override
8 public int add(User user) {
9 userMapper.insert(user);
10 int id = user.getId();
11 return id;
12 }
13
14 }
Controller层的UserController
1 @RestController
2 @RequestMapping("/api/v1/user")
3 public class UserController {
4
5
6 @Autowired
7 private UserService userService;
8
9 @Autowired
10 private UserMapper userMapper;
11
12
13 /**
14 * 功能描述: user 保存接口
15 * @return
16 */
17 @GetMapping("add")
18 public Object add(){
19
20 User user = new User();
21 user.setAge(11);
22 user.setCreateTime(new Date());
23 user.setName("xdclass");
24 user.setPhone("10010000");
25 int id = userService.add(user);
26
27 return JsonData.buildSuccess(id);
28 }
29
30
31
32 /**
33 * 功能描述:查找全部用户
34 * @return
35 */
36 @GetMapping("findAll")
37 public Object findAll(){
38
39 return JsonData.buildSuccess(userMapper.getAll());
40 }
41
42
43
44 @GetMapping("find_by_id")
45 public Object findById(long id){
46 return JsonData.buildSuccess(userMapper.findById(id));
47 }
48
49
50 @GetMapping("del_by_id")
51 public Object delById(long id){
52 userMapper.delete(id);
53 return JsonData.buildSuccess();
54 }
55
56 @GetMapping("update")
57 public Object update(String name,int id){
58 User user = new User();
59 user.setName(name);
60 user.setId(id);
61 userMapper.update(user);
62 return JsonData.buildSuccess();
63 }
64
65 }
来源:oschina
链接:https://my.oschina.net/u/4334770/blog/3298704