常见的Java持久化框架有哪些?

  • Post category:Java

常见的Java持久化框架包括JPA(Java Persistence API)、Hibernate、MyBatis和Spring Data JPA等。下面将逐一介绍这些框架及其使用攻略。

JPA

Java Persistence API(JPA)是一组用于Java应用程序访问关系型数据库的API。JPA是基于Hibernate实现的,它将对象关系映射(ORM)与面向对象编程相结合,使得开发人员可以不用编写SQL语句,而是通过定义实体类和注解来实现对象关系的映射。

使用攻略

  1. 添加依赖

在Maven项目的pom.xml文件中,添加如下依赖:

xml
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>

  1. 定义实体类

在Java程序中定义实体类,例如:

“`java
import javax.persistence.*;

@Entity
@Table(name = “users”)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;

   // getters and setters

}
“`

  1. 配置persistence.xml

在Java项目的src/main/resources/META-INF目录下,创建persistence.xml文件,并添加如下配置:

xml
<persistence-unit name="my-persistence-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>

  1. 编写代码

在Java程序中,使用EntityManagerFactoryEntityManager来访问数据库,例如:

“`java
import javax.persistence.*;
import java.util.List;

public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(“my-persistence-unit”);
EntityManager entityManager = entityManagerFactory.createEntityManager();

       // insert
       entityManager.getTransaction().begin();
       User user = new User();
       user.setName("Alice");
       user.setAge(20);
       entityManager.persist(user);
       entityManager.getTransaction().commit();

       // select
       TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u", User.class);
       List<User> userList = query.getResultList();
       System.out.println(userList);

       entityManager.close();
       entityManagerFactory.close();
   }

}
“`

Hibernate

Hibernate是一个ORM框架,它可以将Java对象映射到关系型数据库中的表。Hibernate提供了一套面向对象的API,使得开发人员可以通过操作Java对象,来完成与数据库的交互。

使用攻略

  1. 添加依赖

在Maven项目的pom.xml文件中,添加如下依赖:

xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>

  1. 定义实体类

在Java程序中定义实体类,例如:

“`java
import javax.persistence.*;

@Entity
@Table(name = “users”)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;

   // getters and setters

}
“`

  1. 编写代码

在Java程序中,使用SessionFactorySession来访问数据库,例如:

“`java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.List;

public class Main {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();

       // insert
       Transaction transaction = session.beginTransaction();
       User user = new User();
       user.setName("Bob");
       user.setAge(30);
       session.persist(user);
       transaction.commit();

       // select
       List<User> userList = session.createQuery("FROM User", User.class).list();
       System.out.println(userList);

       session.close();
       sessionFactory.close();
   }

}
“`

MyBatis

MyBatis是一个数据持久层框架,它提供了一种将Java对象和SQL语句进行映射的方式,可以将SQL语句写在XML文件中,也可以使用注解的方式来定义SQL语句。

使用攻略

  1. 添加依赖

在Maven项目的pom.xml文件中,添加如下依赖:

xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>

  1. 编写Mapper接口和XML文件

定义Mapper接口和Mapper XML文件,例如:

“`java
public interface UserMapper {
@Insert(“INSERT INTO users(name, age) VALUES(#{name}, #{age})”)
void insert(User user);

   @Select("SELECT * FROM users")
   List<User> selectAll();

}
“`

“`xml



INSERT INTO users(name, age) VALUES(#{name}, #{age})

“`

  1. 配置SqlSessionFactory

配置SqlSessionFactory,例如:

“`java
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = “mybatis-config.xml”;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
“`

  1. 编写代码

在Java程序中,使用SqlSession来访问数据库,例如:

“`java
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class Main {
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();

       // insert
       UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
       User user = new User();
       user.setName("Charlie");
       user.setAge(40);
       userMapper.insert(user);
       sqlSession.commit();

       // select
       List<User> userList = userMapper.selectAll();
       System.out.println(userList);

       sqlSession.close();
   }

}
“`

Spring Data JPA

Spring Data JPA是Spring项目中的一个模块,它是JPA规范的补充,提供了更为灵活和强大的持久化功能。

使用攻略

  1. 添加依赖

在Maven项目的pom.xml文件中,添加如下依赖:

xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>

  1. 定义实体类

在Java程序中定义实体类,例如:

“`java
import javax.persistence.*;

@Entity
@Table(name = “users”)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;

   // getters and setters

}
“`

  1. 定义Repository接口

定义Repository接口,例如:

“`java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository {
}
“`

  1. 编写代码

在Java程序中,使用Repository来访问数据库,例如:

“`java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.List;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

       // insert
       UserRepository userRepository = context.getBean(UserRepository.class);
       User user = new User();
       user.setName("David");
       user.setAge(50);
       userRepository.save(user);

       // select
       List<User> userList = userRepository.findAll();
       System.out.println(userList);

       context.close();
   }

}
“`

以上就是常见的Java持久化框架的使用攻略。其中,JPA和Hibernate适用于紧耦合的开发,MyBatis适用于松耦合的开发,而Spring Data JPA则提供了更为灵活和强大的持久化功能。