JPA入门级demo
下面来实现一个简单的 jpa工程(入门级工程,仅供了解使用)
1、在eclipse中创建jpa工程(平时都用idea,回过头来用eclipse真是郁闷到死啊!)
2、引入jar包就不多说了
3、编写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的实现 1、实际上配置的是 javax.persistence.spi.PersistenceProvider 接口的实现类 2、若JPA项目中只有一个JPA的实现产品,则也可以不配置该阶段 --> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <!-- 连接数据库的基本信息 --> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="houchen"/> <!-- 配置JPA 实现产品的基本属性,也就是配置hibernate的基本属性 --> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.hbm2ddl.auoto" value="update"/> </properties> </persistence-unit> </persistence>
4、创建实体类并在persistence.xml中添加要持久化的类
//进行映射的表的名称 @Table(name="JPA_CUTOMERS") @Entity public class Customer { private Integer id; private String lastName; private String email; private int age; //生成主键的方式 @GeneratedValue(strategy=GenerationType.AUTO) @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="LAST_NAME",length=50,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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
<!-- 添加持久化类 -->
<class>com.atguigu.jpa.helloworld.Customer</class>
5、进行持久化的测试操作
public class Main { public static void main(String[] args) { //1、创建EntitymanagerFactory String persistenceUnitName ="jpa-1"; EntityManagerFactory entityManagerFactory = Persistence. createEntityManagerFactory(persistenceUnitName); //2、创建EntityManager EntityManager entityManager =entityManagerFactory.createEntityManager(); //3、开启事务 EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //4、进行持久化操作 Customer customer =new Customer(); customer.setAge(12); customer.setEmail("1285653662@qq.com"); customer.setLastName("chen"); entityManager.persist(customer); //5、提交事务 transaction.commit(); //6、关闭entityManager entityManager.close(); //7、关闭entityManagerFactory entityManagerFactory.close(); } }