针对“将原生JDBC封装实现CRUD的案例”的完整攻略,我来为您进行详细讲解。
什么是JDBC?
Java 数据库连接(Java Database Connectivity,简称JDBC),是Java语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了一系列的类和接口,使得Java程序可以方便地对各种关系型数据库进行操作。
为什么需要封装JDBC?
JDBC提供的技术过于原始繁琐,长期使用原生JDBC将会带来很多问题,例如代码冗余、维护成本较高、易错等。因此,一些开发者通过封装原生JDBC,将其封装成一个类库、框架,业务开发人员可以直接使用统一且简洁的接口进行数据库操作,从而提高开发效率。
封装JDBC实现CRUD示例
为了展示如何封装原生JDBC实现CRUD,我们提供以下两个示例。
示例一:连接池封装
- 首先,需要导入以下依赖:
<!-- 数据库连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
<!-- JdbcTemplate依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
- 定义一个连接池,通过连接池类的getDataSource()方法获取JdbcTemplate对象。
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
/**
* 数据库连接池
*/
public class DbPool {
private final DruidDataSource dataSource;
public DbPool() {
dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
}
public DataSource getDataSource() {
return dataSource;
}
}
- 封装基于JdbcTemplate的数据库操作类
JdbcTemplate是Spring Framework提供的一个用于简化JDBC操作的工具类。在此基础上,我们可以很方便地进行增删改查操作。
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
/**
* 封装基于JdbcTemplate的数据库操作类
*/
public class Dao {
private final JdbcTemplate jdbcTemplate;
public Dao() {
DataSource dataSource = new DbPool().getDataSource();
jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<User> queryAll() {
String sql = "select * from user";
List<User> userList = jdbcTemplate.query(sql, new UserMapper());
return userList;
}
public int insert(User user) {
String sql = "insert into user(name, age) values (?, ?)";
Object[] params = {user.getName(), user.getAge()};
int rows = jdbcTemplate.update(sql, params);
return rows;
}
public int update(User user) {
String sql = "update user set name = ?, age = ? where id = ?";
Object[] params = {user.getName(), user.getAge(), user.getId()};
int rows = jdbcTemplate.update(sql, params);
return rows;
}
public int delete(Long id) {
String sql = "delete from user where id = ?";
Object[] params = {id};
int rows = jdbcTemplate.update(sql, params);
return rows;
}
}
示例二:ORM框架封装
在封装JDBC的过程中,ORM(对象关系映射)框架也是非常常见的一种方式。Hibernate和MyBatis是两个比较流行的ORM框架。
在这里,我们以MyBatis为例,详细演示如何封装原生JDBC。
- 步骤一:在pom.xml中导入以下依赖
<!-- MySQL Connector驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- Spring Framework依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
- 步骤二:在resource目录下定义以下两个文件:
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>
<typeAliases>
<typeAlias alias="User" type="com.example.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/UserMapper.xml"/>
</mappers>
</configuration>
UserMapper.xml文件,这个文件定义了SQL语句和结果映射。
<?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.UserMapper">
<resultMap id="BaseResultMap" type="User">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="age" jdbcType="INTEGER" property="age"/>
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
select *
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select *
from user
</select>
<insert id="insert" parameterType="User">
insert into user (name, age)
values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
</insert>
<update id="update" parameterType="User">
update user
set
name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=BIGINT}
</update>
<delete id="delete" parameterType="java.lang.Long">
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
</mapper>
- 步骤三:定义相应的User实体类,如下所示:
public class User {
private Long id;
private String name;
private Integer age;
// setter和getter方法
}
- 步骤四:定义UserMapper接口,如下所示:
public interface UserMapper {
User selectById(Long id);
List<User> selectAll();
int insert(User user);
int update(User user);
int delete(Long id);
}
- 步骤五:定义基于MyBatis的DAO,通过SqlSession连接Mapper接口。
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* 基于MyBatis的DAO
*/
public class UserDao {
private final SqlSession sqlSession;
public UserDao() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
}
public User selectById(Long id) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.selectById(id);
}
public List<User> selectAll() {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.selectAll();
}
public int insert(User user) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int rows = userMapper.insert(user);
sqlSession.commit();
return rows;
}
public int update(User user) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int rows = userMapper.update(user);
sqlSession.commit();
return rows;
}
public void delete(Long id) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.delete(id);
sqlSession.commit();
}
}
至此,我们已经学会了如何利用MyBatis框架,将原生JDBC封装实现CRUD的案例。
希望本文的讲解能够对您有所帮助,谢谢!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:将原生JDBC封装实现CRUD的案例 - Python技术站