JPA入门实例

来源:互联网 发布:plc电路图绘制软件 编辑:程序博客网 时间:2024/06/08 08:54

工程目录:
这里写图片描述

(注意:persistence.xml文件的位置决定持久性的根(Persistence Root)。持久性的根为JAR文件或者包含META-INF目录(前提是persistence.xml位于此)的目录。一般将这个persistence.xml文件放在src下的META-INF中。命名及位置都不能变)

a)、导入相关jar包和创建META-INF和persistence.xml文件.

persistence.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">      <persistence-unit name="mysqlJPA" transaction-type="RESOURCE_LOCAL">    <provider>org.hibernate.ejb.HibernatePersistence</provider>     <class>com.jpa.entity.Person</class>     <class>com.jpa.entity.UserInfo</class>     <class>com.jpa.entity.AccountInfo</class>         <properties>             <property name="hibernate.connection.driver_class"              value="com.mysql.jdbc.Driver"/>             <property name="hibernate.connection.url"            value="jdbc:mysql://localhost:3306/test"/>             <property name="hibernate.connection.username" value="root"/>             <property name="hibernate.connection.password" value=""/>             <property name="hibernate.dialect"            value="org.hibernate.dialect.MySQL5Dialect"/>             <property name="hibernate.show_sql" value="true"/>             <property name="hibernate.format_sql" value="true"/>             <property name="hibernate.use_sql_comments" value="false"/>             <property name="hibernate.hbm2ddl.auto" value="update"/>         </properties>     </persistence-unit>  </persistence>  

可以选择性加入spring依赖:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">    <context:component-scan base-package="com.jpa"/>    <tx:annotation-driven transaction-manager="transactionManager"/>    <jpa:repositories base-package="com.jpa.dao"  repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">        <property name="entityManagerFactory" ref="entityManagerFactory"/>    </bean>    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">            <property name="jpaVendorAdapter">                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">                <property name="generateDdl" value="false"/>                <property name="showSql" value="true"/>            </bean>            </property>    </bean></beans>

b)、编写实体bean,如下:

package com.jpa.entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Person {    private int id;      private String name;      @Id @GeneratedValue      public int getId() {          return id;      }      public void setId(int id) {          this.id = id;      }      @Column(length=12)      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }    @Override    public String toString() {        return "Person [id=" + id + ", name=" + name + "]";    }  }

c)、编写junit测试代码,如下:

package com.jpa.test;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import org.hibernate.sql.Update;import com.jpa.entity.Person;import com.jpa.service.UserServiceImpl;public class JpaTest {    public void createTable(){          //可以验证生成表是否正确          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          factory.close();      }     public static  void save(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          em.getTransaction().begin();          Person person = new Person(); //person为new状态          person.setName("zhang san");          em.persist(person); //持久化实体          em.getTransaction().commit();          em.close();          factory.close();      }      //new 、托管、脱管、删除      public static void update(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          em.getTransaction().begin();          Person person = em.find(Person.class, 1);          person.setName("hmk"); //person为托管状态          em.getTransaction().commit();          em.close();          factory.close();      }      public void update2(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          em.getTransaction().begin();          Person person = em.find(Person.class, 1);          em.clear(); //把实体管理器中的所有实体变为脱管状态          person.setName("hmk2");          em.merge(person); //把脱管状态变为托管状态,merge可以自动选择insert or update 数据          em.getTransaction().commit();          em.close();          factory.close();      }       public void remove(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          em.getTransaction().begin();          Person person = em.find(Person.class, 1);          em.remove(person); //删除实体          em.getTransaction().commit();          em.close();          factory.close();      }      public static void find(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          Person person = em.find(Person.class, 1); //类似于hibernate的get方法,没找到数据时,返回null          System.out.println(person);          em.close();          factory.close();      }      public static void find2(){          EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");          EntityManager em = factory.createEntityManager();          Person person = em.getReference(Person.class, 2); //类似于hibernate的load方法,延迟加载.没相应数据时会出现异常          System.out.println(person.getName()); //真正调用时才查找数据          em.close();          factory.close();      }      public static void main(String[] args) {          find();         //new UserServiceImpl().createNewAccount("ZhangJianPing", "123456", 1);     }}
原创粉丝点击