JPA学习笔记【二】【helloworld】

来源:互联网 发布:淘宝平台入驻协议 编辑:程序博客网 时间:2024/06/06 14:01

使用JPA持久化对象的步骤




此处有个小问题,在创建JPA工程的时候,提示下图这样一个问题,at least one user library must be selected,不解决则无法创建这个工程,网上搜索了下,参考http://www.cnblogs.com/lj95801/p/5001882.html解决了此问题。




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">


<!-- 配置使用什么ORM产品来做作为JPA的实现 1.实际上配置的是javax.persistence.spi.PersistenceProvider接口的实现类 
2.若JPA项目中只有一个JPA实现产品,则也可以不配置该节点 -->


<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.abcd.helloworld.Customer</class>


<properties>
<!-- 链接数据库的基本信息 -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/jpa" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="1234" />




<!-- 配置JPA实现产品的基本属性,配置Hibernate的基本属性 -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>


</properties>
</persistence-unit>
</persistence>

```

测试代码

```

//1.创建EntityManagerFactory
String persistenceUnitName = "jpa-1";
EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);
//2.创建 EntityManageer
EntityManager manager = factory.createEntityManager();
//3.开启事务
EntityTransaction traction =  manager.getTransaction();
traction.begin();
System.out.println(traction);
//4.进行持久化操作
Customer customer = new Customer();
customer.setAge(11);
customer.setEmail("abc@abcd.com");
customer.setLastName("tom");
manager.persist(customer);
//5.提交事务
traction.commit();
//6.关闭EntityManager
manager.close();
//7.关闭EntityManagerFactory
factory.close();

```

0 0
原创粉丝点击