基础测试:
第一步:配置依赖:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.7.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.33</version> </dependency>
第二步:在classpath路径下,添加META-INF文件夹,添加peristence.xml文件.
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <!-- 持久化单元.一个持久化单元可以创建一个EntityManagerFactory --> <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/tests" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <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" /> <!-- 设置外连接抓取树的最大深度 --> <property name="hibernate.max_fetch_depth" value="3"/> </properties> </persistence-unit> </persistence>
@Entity @Table(name="t_person") public class Person { //主键 @Id //主键策略 @GeneratedValue(strategy=GenerationType.AUTO) private Long id; //名字 @Column(name="name",length=10,nullable=false) private String name; //生日 日期 @Temporal(TemporalType.DATE) private Date birthday;//日期:date 日期时间: timestamp ,时间:time //枚举 EnumType.ORDINAL 保存索引 @Enumerated(EnumType.STRING)//保存字符串 @Column(length=5,nullable=false) private Gender gender=Gender.MAN; //大文本>>>字符 @Lob private String info; //大文本>>>字节 @Lob //抓取策略 FetchType.EAGER :立即加载,FetchType.LAZY:延迟加载 @Basic(fetch=FetchType.LAZY) private Byte[] file; //不让这个属性跟数据库进行映射.不进行注解,默认进行映射 @Transient private String imagePath; //省略get/set方法... }
枚举类:
public enum Gender { MAN,WOMEN }
使用Junit进行测试:
public class TestJPA { EntityManagerFactory emf = null; @Before public void before() { emf = Persistence.createEntityManagerFactory("myJPA"); } /** * </pre> 添加一个用户 </pre> */ @Test public void addPerson() { Person user = new Person(); user.setName("哈哈"); user.setBirthday(new Date()); // 创建实体管理器对象 EntityManager em = emf.createEntityManager(); // 开启事务 em.getTransaction().begin(); // 持久化对象 em.persist(user); // 提交事务 em.getTransaction().commit(); // 关闭entityManager em.close(); } /** * 查询用户 find相当于hibernate的get.立即加载 没有记录,返回null */ @Test public void getPerson() { // 创建实体管理器对象 EntityManager em = emf.createEntityManager(); Person person = em.find(Person.class, 2L); System.out.println(person); // 关闭entityManager em.close(); } /** * getReference:相当于heibernate的load方法 ,延迟加载,返回代理对象 没有记录,抛出异常 * javax.persistence.EntityNotFoundException: Unable to find * com.zt.entity.Person with id 2 */ @Test public void getPerson2() { // 创建实体管理器对象 EntityManager em = emf.createEntityManager(); Person person = em.getReference(Person.class, 2L); System.out.println(person); // 关闭entityManager em.close(); } /** * 修改用户. jpa实体的状态: 1,new. 2,托管. 3,游离状态. 4.删除状态 */ @Test public void modifyPerson() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // 查找ID为1的user,进行修改 Person person = em.find(Person.class, 3L);// 托管状态 person.setName("我被修改了"); em.getTransaction().commit(); em.close(); } @Test public void modifyPerson2() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // 查找ID为1的user,进行修改 Person person = em.find(Person.class, 1L);// 托管状态 em.clear();// 把实体管理器中的所有实体变成游离状态 person.setName("我被修改了"); em.merge(person);// 把在游离状态的实体更新同步至数据库 em.getTransaction().commit(); em.close(); } /** * 删除用户 */ @Test public void deletePerson() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // 查找id为1的用户删除掉 Person person = em.find(Person.class, 2L); em.remove(person); em.getTransaction().commit(); em.close(); } // ----------------------查询语句---------------------------------- /** * </pre> JPQL: JPA规范需要写上select 别名. 如果使用hibernate实现jpa,可以省略 </pre> */ @Test public void query() { EntityManager em = emf.createEntityManager(); Query query = em.createQuery("select o from Person o where o.id=?1"); query.setParameter(1, 1L); // query.getResultList();//集合 相当于hibernate list() Person person = (Person) query.getSingleResult();// 唯一结果 // 相当于hibernate的uniqueResult() System.out.println(person); em.close(); } @Test public void delete() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Query query = em.createQuery("delete from Person o where o.id=?1"); query.setParameter(1, 1L).executeUpdate(); em.getTransaction().commit(); em.close(); } @Test public void update() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.createQuery("update from Person o set o.name=:name where o.id=?1")// .setParameter(1, 2L)// .setParameter("name", "嘻嘻")// .executeUpdate(); em.getTransaction().commit(); em.close(); } /** * 关闭EntityManagerFactory */ @After public void after() { if (null != emf) { emf.close(); } } }