配置jpa

时间:2023-06-02 22:57:56

配置jpa

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">
<!--
配置使用什么 ORM 产品来作为 JPA 的实现
. 实际上配置的是 javax.persistence.spi.PersistenceProvider 接口的实现类
. 若 JPA 项目中只有一个 JPA 的实现产品, 则也可以不配置该节点.
-->
<provider>org.hibernate.ejb.HibernatePersistence</provider> <!-- 添加持久化类 -->
<class>com.jpa.main.Customer</class>
<class>com.jpa.main.Order</class> <class>com.jpa.main.Department</class>
<class>com.jpa.main.Manager</class> <class>com.jpa.main.Item</class>
<class>com.jpa.main.Category</class> <!--
配置二级缓存的策略
ALL:所有的实体类都被缓存
NONE:所有的实体类都不被缓存.
ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存
DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类
UNSPECIFIED:默认值,JPA 产品默认值将被使用
-->
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <properties>
<!-- 连接数据库的基本信息 -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///ssh01"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="wzy123"/> <!-- 配置 JPA 实现产品的基本属性. 配置 hibernate 的基本属性 -->
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/> <!-- 二级缓存相关 -->
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
</properties>
</persistence-unit>
</persistence>
测试类

package com.jpa.main;

import java.util.Date;
import java.util.HashMap;
import java.util.Map; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence; public class Main { public static void main(String[] args) { //1. 创建 EntitymanagerFactory
String persistenceUnitName = "jpa-1"; Map<String, Object> properites = new HashMap<String, Object>();
properites.put("hibernate.show_sql", true); EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory(persistenceUnitName);
//Persistence.createEntityManagerFactory(persistenceUnitName, properites);
//使用这个构造器可以添加一些属性
          //但必须是这样的<property name="hibernate.show_sql" value="true"/> //2. 创建 EntityManager. 类似于 Hibernate 的 SessionFactory
EntityManager entityManager = entityManagerFactory.createEntityManager(); //3. 开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin(); //4. 进行持久化操作
Customer customer = new Customer();
customer.setAge();
customer.setEmail("tom@atguigu.com");
customer.setLastName("Tom");
customer.setBirth(new Date());
customer.setCreatedTime(new Date()); entityManager.persist(customer);//保存操作 //5. 提交事务
transaction.commit(); //6. 关闭 EntityManager
entityManager.close(); //7. 关闭 EntityManagerFactory
entityManagerFactory.close();
} }
实体类映射

package com.jpa.main;
import java.util.Date;
import java.util.HashSet;
import java.util.Set; import javax.persistence.Basic;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient; @Table(name="JPA_CUTOMERS")
@Entity
public class Customer { private Integer id;
private String lastName; private String email;
private int age; private Date createdTime;
private Date birth; public Customer() {
// TODO Auto-generated constructor stub
} public Customer(String lastName, int age) {
super();
this.lastName = lastName;
this.age = age;
}// @TableGenerator(name="ID_GENERATOR", //Table主键生成策略,不常用
// table="jpa_id_generators",
// pkColumnName="PK_NAME",
// pkColumnValue="CUSTOMER_ID",
// valueColumnName="PK_VALUE",
// allocationSize=100)//id每次增长100
// @GeneratedValue(strategy=GenerationType.TABLE,generator="ID_GENERATOR")
//注解一般标注在get方法上
@GeneratedValue(strategy=GenerationType.AUTO)//生成主键的方式
@Id
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} @Column(name="LAST_NAME",length=,nullable=false)
public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
}
@Basic//不写默认是这个注解,字段名就是这个名
public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Temporal(TemporalType.TIMESTAMP)//日期格式化@Temporal
public Date getCreatedTime() {
return createdTime;
} public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
} @Temporal(TemporalType.DATE)
public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
} //工具方法. 不需要映射为数据表的一列.表示这只是一个普通方法 ,和数据表字段无关
@Transient
public String getInfo(){
return "lastName: " + lastName + ", email: " + email;
} @Override
public String toString() {
return "Customer [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", age=" + age + ", createdTime=" + createdTime
+ ", birth=" + birth + "]";
} }