jdbc,java database connectivity,是java连接数据库操作的原生接口。jdbc是所有框架操作数据库所必须的,是数据库的统一接口标准。 orm,object relational mapping,一般指对象关系映射,是通过使用描述对象和数据库之间映射的元数据,将面向对象语言程序中的对象自动持久化到关系数据库中。 jpa,是orm框架的统一接口标准,即orm框架的规范。 hibernate,是一个标准的orm框架,实现了jpa接口,可理解成jpa是接口,hibernate是实现类。 spring data jpa,是对jpa规范的再次抽象,底层还是用的hibernate,简化了数据库访问。 mybatis,是一个半orm框架,因为hibernate不需要写sql,而mybatis需要写sql。
jdbc、hibernate、mybatis的区别
- jdbc是较底层的持久化操作方式,而hibernate和mybatis都是在jdbc的基础上进行了封装使其更加方便程序运对持久层的操作。
- jdbc就是先创建connection连接数据库,然后创建statement对象,通过statement对象执行sql语句,得到resultSet对象,通过对resultSet对象的遍历操作来获取数据并手动转为javaBean,最后关闭resultSet、statement、connection释放资源;hibernate是将数据库中的数据表映射为持久层的java对象,对sql语句修改和优化困难;mybatis将sql语句的输入参数和输出参数映射为java对象,sql语句修改和优化方便;
- 若进行底层编程,且对性能要求极高的话,应采用jdbc方式;若对数据库进行完整性控制的话建议使用hibernate;若灵活使用sql语句的话建议使用mybatis框架;
jdbc实例 jdbc工具类,封装jdbc通用方法,包括驱动加载、数据库连接、资源释放
public class JdbcUtil {
private static final String DRIVERNAME = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
/**
* JDBC编程步骤:
* 1、加载驱动(Driver)
* 2、获取连接(Connection)
* 3、创建Statement对象(Statement、PreparedStatement)
* 4、执行SQL(execute、executeUpdate、executeQuery)
* 5、释放资源。
*/
//1、加载驱动,在整个过程过只要加载一次,我这里在静态块中进行加载
static {
try {
Class.forName(DRIVERNAME);
} catch (Exception e) {
e.printStackTrace();
System.out.println("驱动加载失败!");
}
}
//2、驱动加载完成后,获取Connection连接对象,在整个过程中需要进行多次获取
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
//3、创建Statement对象,代码未写在该类中,写在了***Dao类中,案例通过PreparedStatement进行预编译
//4、执行SQL语句并获取结果集,代码未写在该类中,写在了***Dao类中
//5、释放资源,因为在数据库的增删该查中涉及到有结果集的和没有结果集的,所有对释放资源的方法进行了重载
//5.1、增加、修改、删除操作时不带ResultSet,用该方法释放资源
public static void release(Connection conn, Statement stmt) {
//关闭Connection连接
if (conn != null) {
try {
conn.close();
System.out.println("Connection连接已关闭!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Connection连接关闭失败!");
}
}
//关闭Statement对象
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Statement对象关闭失败!");
}
}
}
//5.2、查询操作时带ResultSet,用该方法释放资源
public static void release(Connection conn, Statement stmt, ResultSet rs) {
//关闭Connection连接
if (conn != null) {
try {
conn.close();
System.out.println("Connection连接已关闭!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Connection连接关闭失败!");
}
}
//关闭Statement对象
if (stmt != null) {
try {
stmt.close();
System.out.println("Statement对象已关闭!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Statement对象关闭失败!");
}
}
//关闭ResultSet结果集
if (rs != null) {
try {
rs.close();
System.out.println("ResultSet结果集已关闭!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("ResultSet结果集关闭失败!");
}
}
}
}
dao类,实现数据库中的增删改查方法
public class DataBaseDao {
/**
* 保存用户信息到数据库中
*
* @param
*/
public void save(User user) {
Connection conn = null;
PreparedStatement preparedStatement = null;
//定义保存的SQL语句
String sql = "insert into user values(?,?,?)";
try {
//建立数据库连接
conn = JdbcUtil.getConnection();
//创建Statement对象,对SQL语句进行预编译
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, user.getId());
preparedStatement.setString(2, user.getName());
preparedStatement.setString(3, user.getContent());
//执行SQL语句
int i = preparedStatement.executeUpdate();
System.out.println("保存成功!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("保存失败!");
}
//执行完成后关闭连接,释放资源,此方法为保存,无结果集,调用release(Connection conn,Statement stmt)
JdbcUtil.release(conn, preparedStatement);
}
/**
* 通过ID查询数据库中的用户信息
*
* @param id
*/
public User queryById(Integer id) {
//创建用户对象
User user = null;
Connection conn = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//定义根据ID查询的SQL语句
String sql = "select * from user where id =?";
try {
//建立数据库连接
conn = JdbcUtil.getConnection();
//创建Statement对象并对SQL语句进行预编译
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, id);
//获取结果集
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Integer userId = resultSet.getInt(1);
String name = resultSet.getString(2);
String content = resultSet.getString(3);
user = new User();
user.setId(userId);
user.setName(name);
user.setContent(content);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("查询失败!");
}
//查询完成后断开连接,释放资源
JdbcUtil.release(conn, preparedStatement, resultSet);
//返回对象,后面的测试类中获取对象并打印
return user;
}
/**
* 查询所有用户信息
*/
public List<User> queryAll() {
//创建User对象
User user = null;
//创建一个list,后面读取的用户信息保存在list中
List<User> list = new ArrayList<>();
Connection conn = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//定义一个查询所有信息的SQL语句
String sql = "select * from user";
try {
//建立Connection连接
conn = JdbcUtil.getConnection();
//创建Statement对象并对SQL语句进行预编译
preparedStatement = conn.prepareStatement(sql);
//执行SQL语句获取结果集
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Integer userId = resultSet.getInt(1);
String name = resultSet.getString(2);
String content = resultSet.getString(3);
user = new User();
user.setId(userId);
user.setName(name);
user.setContent(content);
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据查询失败!");
}
//查询结束后断开Connection等连接,释放资源
JdbcUtil.release(conn, preparedStatement, resultSet);
//返回list集合
return list;
}
/**
* 修改用户信息并更新数据表
*/
public void updateById(User user) {
Connection conn = null;
PreparedStatement preparedStatement = null;
//定义一个update的SQL语句
String sql = "update user set name=?,content=? where id=?";
try {
//创建数据库连接
conn = JdbcUtil.getConnection();
//创建Statement对象并对SQL语句进行预编译
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getContent());
preparedStatement.setInt(3, user.getId());
//执行SQL语句
int i = preparedStatement.executeUpdate();
System.out.println("更新成功!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("更新失败!");
}
//更新完成后,断开连接,释放资源
JdbcUtil.release(conn, preparedStatement);
}
/**
* 根据ID删除用户信息
*
* @param id
*/
public void deleteById(Integer id) {
Connection conn = null;
PreparedStatement preparedStatement = null;
//定义一个delete的SQL语句
String sql = "delete from user where id = ?";
try {
//建立数据库连接
conn = JdbcUtil.getConnection();
//创建Statement对象并对SQL语句进行预编译
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, id);
//执行SQL语句
int i = preparedStatement.executeUpdate();
System.out.println("删除成功!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("删除失败!");
}
//删除完成后,断开连接,释放资源
JdbcUtil.release(conn, preparedStatement);
}
}
测试
public class AppTest {
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue() {
assertTrue(true);
}
@Test
//保存用户信息
public void save() {
DataBaseDao dao = new DataBaseDao();
User user = new User(11, "caocao", "111");
dao.save(user);
}
@Test
//根据ID查找用户信息
public void queryById() {
DataBaseDao dao = new DataBaseDao();
User user = dao.queryById(11);
System.out.println(user);
}
@Test
//查找全部用户信息
public void queryAll() {
DataBaseDao dao = new DataBaseDao();
List<User> list = dao.queryAll();
for (User user : list) {
System.out.println(user);
}
}
@Test
//更新用户信息
public void update() {
DataBaseDao dao = new DataBaseDao();
User user = new User(11, "caocao", "222");
dao.updateById(user);
}
@Test
//根据ID删除用户信息
public void delete() {
DataBaseDao dao = new DataBaseDao();
dao.deleteById(11);
}
}
hibernate实例
public class User {
private Integer id;
private String name;
private String content;
public User() {
}
public User(Integer id, String name, String content) {
this.id = id;
this.name = name;
this.content = content;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", content='" + content + '\'' +
'}';
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ldc.model">
<class name="User" table="user">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<!-- id的自增长方式采用数据库的本地方式 -->
<generator class="native"/>
</id>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="content" type="java.lang.String">
<column name="content"/>
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="com/ldc/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
pom中引入依赖及设置映射
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
测试
@Test
public void test() {
//1.创建SessionFactory对象
SessionFactory sessionFactory = null;
//创建Configuration,对应hibernate基本配置信息,和对象文件映射信息
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
//2.创建Session对象
Session session = sessionFactory.openSession();
//3.开启事务
Transaction transaction = session.beginTransaction();
//4.执行操作
//新增数据
// User user = new User(11,"caocao","111");
// session.save(user);
//查找数据
// User user2 = session.get(User.class, 2);
// System.out.println(user2);
//更新数据
// User user3 = new User();
// user3.setId(6);
// user3.setName("caocao");
// user3.setContent("666");
// session.update(user3);
//删除数据
// User user4 = new User();
// user4.setId(7);
// session.delete(user4);
//5.提交事务
transaction.commit();
//6.关闭Session
session.close();
//7.关闭SessionFactory
sessionFactory.close();
}
mybatis实例
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ldc/mapper/UserMapper.xml"/>
</mappers>
</configuration>
public interface UserMapper {
List<User> getAll();
User getUser(int id);
Integer insertUser(User user);
Integer updateUser(User user);
Integer deleteUser(int id);
}
<?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.ldc.mapper.UserMapper">
<resultMap id="resultUser" type="com.ldc.model.User">
<id property="id" column="id"/>
<result property="name" column="uname"/>
</resultMap>
<select id="getAll" resultType="com.ldc.model.User">
select * from user
</select>
<select id="getUser" parameterType="java.lang.Integer" resultMap="resultUser">
select * from user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.ldc.model.User">
insert into user (name,content) values(#{name}, #{content})
</insert>
<update id="updateUser" parameterType="com.ldc.model.User">
update user set name = #{name} where id = #{id}
</update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
</mapper>
测试
@Test
public void test() {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("Mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
//遍历获取
List<User> list = userMapper.getAll();
for (User user : list) {
System.out.println(user);
}
// User user = new User(11, "caocao", "111");
// Integer i = userMapper.insertUser(user);
// User user2 = userMapper.getUser(13);
// System.out.println(user2);
// User user3 = new User(13, "caocao444", "444");
// Integer i = userMapper.updateUser(user3);
Integer i = userMapper.deleteUser(13);
session.commit();
}
|