JPA的分页查询:
第一步:首先要用jap导入依赖:jpa是一种规范,要使用需导入实现了规范的hibernate。
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.hibernate.version>5.0.7.Final</project.hibernate.version>
</properties>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- hibernate对jpa的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${project.hibernate.version}</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${project.hibernate.version}</version>
</dependency>
<!-- log日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- Mysql and MariaDB -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
第二步:需要在resources目录创建固定包META-INF并配置xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<!--需要配置persistence-unit节点
持久化单元:
name:持久化单元名称
transaction-type:事务管理的方式
JTA:分布式事务管理
RESOURCE_LOCAL:本地事务管理
-->
<persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
<!--jpa的实现方式 -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<!-- 数据库信息
用户名,javax.persistence.jdbc.user
密码, javax.persistence.jdbc.password
驱动, javax.persistence.jdbc.driver
数据库地址 javax.persistence.jdbc.url
-->
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
<property name="hibernate.show_sql" value="true" />
<!--update,create,no-->
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
第三步配置实体类映射关系:
主要用到的注解有:
@Entity//类太多,声明我是实体类
@Table(name = "***")//对应数据库名称
@Id//指明属性是id
@GeneratedValue(strategy = GenerationType.IDENTITY)
TABLE,//创建一张表实现自增长,数据库都可以用
SEQUENCE,//oracle序列自增长
IDENTITY,//mysql实现自增长
AUTO;//自己选择
@Column(name = "****")//配置属性和数据库字段的对应关系
第四步:分页查询
EntityManagerFactory factory= Persistence.createEntityManagerFactory("myJpa");
EntityManager em = factory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
//复杂查询无法生成sql语句,提供了jpql。
String jpql="from Customer";
Query query = em.createQuery(jpql);
//开始索引
query.setFirstResult(0);
//每页显示条数
query.setMaxResults(3);
List list = query.getResultList();
tx.commit();
6305



被折叠的 条评论
为什么被折叠?



