在Java开发中,数据库连接是基础中的基础。而MyBatis作为一款优秀的持久层框架,能够帮助我们简化数据库操作,提高开发效率。本文将带领大家从零开始,学会使用MyBatis搭建Java项目的数据库连接,即使你是数据库连接的小白,也能轻松入门实战!
了解MyBatis
MyBatis是一个支持定制化SQL、存储过程以及高级映射的持久层框架。它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。MyBatis通过简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
准备工作
在开始之前,请确保你已经安装了以下软件:
- Java Development Kit (JDK)
- Integrated Development Environment (IDE),如IntelliJ IDEA或Eclipse
- MySQL数据库
第一步:创建数据库和表
首先,我们需要创建一个数据库和一个表。以下是一个简单的SQL示例:
CREATE DATABASE mybatis_example;
USE mybatis_example;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);
第二步:配置MySQL数据库连接
接下来,我们需要在项目中配置MySQL数据库连接。以下是两种常见的配置方式:
1. 使用XML配置
在src/main/resources目录下创建一个名为database.properties的文件,并添加以下内容:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_example?useSSL=false&serverTimezone=UTC
username=root
password=root
然后,在src/main/resources目录下创建一个名为mybatis-config.xml的文件,并添加以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
</configuration>
2. 使用注解配置
在src/main/java目录下创建一个名为com.example.mapper的包,并在该包下创建一个名为UserMapper.java的接口,添加以下内容:
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(int id);
}
在src/main/java目录下创建一个名为com.example.entity的包,并在该包下创建一个名为User.java的类,添加以下内容:
package com.example.entity;
public class User {
private int id;
private String username;
private String password;
// 省略getter和setter方法
}
第三步:编写Mapper文件
在src/main/resources目录下创建一个名为com/example/mapper的包,并在该包下创建一个名为UserMapper.xml的文件,添加以下内容:
<?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.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
第四步:编写Service层
在src/main/java目录下创建一个名为com.example.service的包,并在该包下创建一个名为UserService.java的接口,添加以下内容:
package com.example.service;
import com.example.entity.User;
public interface UserService {
User getUserById(int id);
}
在src/main/java目录下创建一个名为com.example.service.impl的包,并在该包下创建一个名为UserServiceImpl.java的类,添加以下内容:
package com.example.service.impl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class UserServiceImpl implements UserService {
private final SqlSessionFactory sqlSessionFactory;
public UserServiceImpl() {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(
Resources.getResourceAsStream("mybatis-config.xml"));
}
@Override
public User getUserById(int id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
return mapper.getUserById(id);
}
}
}
第五步:编写Controller层
在src/main/java目录下创建一个名为com.example.controller的包,并在该包下创建一个名为UserController.java的类,添加以下内容:
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
}
第六步:启动项目
至此,我们已经完成了MyBatis的配置和数据库连接。现在,我们可以启动项目,并通过访问http://localhost:8080/user/{id}来获取用户信息。
总结
通过本文的介绍,相信你已经学会了如何使用MyBatis搭建Java项目的数据库连接。MyBatis作为一个优秀的持久层框架,能够帮助我们简化数据库操作,提高开发效率。希望本文对你有所帮助,祝你学习愉快!
