首页 > 学院 > 开发设计 > 正文

JPA学习笔记【二】【helloworld】

2019-11-11 05:55:04
字体:
来源:转载
供稿:网友

使用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.创建EntityManagerFactoryString persistenceUnitName = "jpa-1";EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);//2.创建 EntityManageerEntityManager 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.关闭EntityManagermanager.close();//7.关闭EntityManagerFactoryfactory.close();

```


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表