1. Introductino

EntityManager是JPA的一个API,他实现了JPA2.0的程序接口和程序生存周期。

下面将介绍其使用方式。

2. Maven Dependencies

引入Hibernate和mysqlJDBC的依赖:

<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.4.0.Final</version>
</dependency>

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.13</version>
</dependency>

3. Configuration

Movie实体类和数据库中的表一样对应。后面将会说明使用EntityManager的API去操作Movie的对象。

3.1 Defining the Entity

使用@Entity标明其为实体类:

@Entity
@Table(name = "MOVIE")
public class Movie {@Idprivate Long id;private String movieName;private Integer releaseYear;private String language;// standard constructor, getters, setters
}

3.2 The persistence.xml File

当EntityManagerFactory被创建,就会到环境变量中找META-INF/persistence.xml这个文件。

文件内容如下:

<persistence-unit name="com.baeldung.movie_catalog"><description>Hibernate EntityManager Demo</description><class>com.baeldung.hibernate.pojo.Movie</class> <exclude-unlisted-classes>true</exclude-unlisted-classes><properties><property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/><property name="hibernate.hbm2ddl.auto" value="update"/><property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/><property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/><property name="javax.persistence.jdbc.user" value="root"/><property name="javax.persistence.jdbc.password" value="root"/></properties>
</persistence-unit>

这里定义的这些都是persistence-unit,都是被EntityManger所管理。还定义了一些方言集和JDBC的一些属性。

4. Container and Application Managed EntityManager

EntityManager有两种类型:一个是Container-Managed和Application-Managed。

4.1 Container-Managed EntityManager

这里有个很有意思的话:

@PersistenceContext
EntityManager entityManager;

这里的意思难道是使用了XXXManagerFactory就可以变成企业级组件??

这个EntityManager有事务的功能,不需要进行手动关闭,如果强制手动关闭,那么会抛出IllegalStateException异常。

4.2 Application-Managed EntityManger

手动创建一个EntityManager,这个手动创建的EntityManager需要手动进行管理。

如下:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog");

EntityManagerFacotry调用createEntityManager()创建对象:

public static EntityManager getEntityManager() {return emf.createEntityManager();
}

这种EntityManger需要手动关闭。

4.3 Thread-Safety

EntityManagerFactory实例以及Hiberante的SessionFactory实例,都是线程安全了。

在多线程中完整的创建如下:

EntityManagerFactory emf = // fetched from somewhere
EntityManager em = emf.createEntityManager();

EntityManger是现场不安全的,所以每个现场都要创建一个这样的实例,并且还要进行关闭,如下:

EntityManagerFactory emf = // fetched from somewhere
EntityManager em = emf.createEntityManager();
// use it in the current thread

或者使用这种方式:

@Service
public class MovieService {@PersistenceContext // or even @Autowiredprivate EntityManager entityManager;// omitted
}

5. Hibernate Entity Operations

EntityManger的API提供了与数据库交互的方法。

5.1 Persisting Entities

保存一个对象:

public void saveMovie() {EntityManager em = getEntityManager();em.getTransaction().begin();Movie movie = new Movie();movie.setId(1L);movie.setMovieName("The Godfather");movie.setReleaseYear(1972);movie.setLanguage("English");em.persist(movie);em.getTransaction().commit();
}

5.2 Loading Entities

使用find()方法用于检索数据:

public Movie getMovie(Long movieId) {EntityManager em = getEntityManager();Movie movie = em.find(Movie.class, new Long(movieId));em.detach(movie);return movie;
}

如果只需要引用实体,调用getReference()方法,他会从代理中返回实体:

Movie movieRef = em.getReference(Movie.class, new Long(movieId));

5.3 Detaching Entities

将实体从持久层分离,调用detach()方法。

em.detach(movie);

5.4 Merging Entities

合并实体仿事务的操作,防止并发性的问题。

public void mergeMovie() {EntityManager em = getEntityManager();Movie movie = getMovie(1L);em.detach(movie);movie.setLanguage("Italian");em.getTransaction().begin();em.merge(movie);em.getTransaction().commit();
}

5.5 Querying for Entities

使用JPQL进行查询:

public List<?> queryForMovies() {EntityManager em = getEntityManager();List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1").setParameter(1, "English").getResultList();return movies;
}

5.6 Removing Entities

使用remove()方法移除元素:

public void removeMovie() {EntityManager em = HibernateOperations.getEntityManager();em.getTransaction().begin();Movie movie = em.find(Movie.class, new Long(1L));em.remove(movie);em.getTransaction().commit();
}

Java文档阅读笔记-Guide to the Hibernate EntityManager相关推荐

  1. Java文档阅读笔记-EJB Tutorial

    目录 Introduction to EJB What is EJB Introduction to EJB EJB(Enterprise Java Bean)Java企业组建:用于开发分布式.健全. ...

  2. Java文档阅读笔记-C3P0连接池的使用

    这篇博文如何在应用程序中使用和配置C3P0 prom.xml如下: <dependency><groupId>com.mchange</groupId><ar ...

  3. Java文档阅读笔记-JPA Tutorial

    目录 JPA Tutorial JPA Intrduction JPA Object Relational Mapping Types of Mapping JPA Tutorial JPA(Java ...

  4. Java文档阅读笔记-JDBC Driver

    目录 JDBC Driver JDBC-ODBC bridge driver Native-API driver Network Protocol driver Thin driver JDBC Dr ...

  5. Java文档阅读笔记-JPA中getOne()和findById的区别

    findById()和getOne()都是从数据库中检索某个对象,不过获取数据的方式是不同的,getOne()是lazy操作,这种操作甚至没有访问数据库. getOne() 返回ID的引用对象,他内部 ...

  6. Java文档阅读笔记-Spring Boot JDBC

    Spring Boot JDBC提供了使用引导和相关驱动去连接某数据库引用. 在Spring Boot JDBC中与数据库相关的bean有DataSouce,JdbcTemplate,NamedPar ...

  7. Qt文档阅读笔记-共享库的创建与调用

    使用共享库的符号 这个符号可以作用在变量.类.函数中,并且这些都可以被调用端使用. 在编译共享库中,需要使用export符号.在使用端调用的时候使用import符号. 这里是本人从文档中记录的笔记,大 ...

  8. Qt文档阅读笔记-加载HeightMap(高度图)构造3D地形图

    Qt文档阅读笔记-加载HeightMap(高度图)构造3D地形图 QHeightMapSurfaceDataProxy:是Q3DSurface的一个基本代理类. 他是专门加载高度图. 高度图是没有X, ...

  9. Qt文档阅读笔记-Rotations Example相关

    Rotations Example文档阅读笔记 使用这种方式,对y轴和z轴进行旋转. QQuaternion yRotation = QQuaternion::fromAxisAndAngle(0.0 ...

最新文章

  1. Exchange 2007 配置POP3
  2. 将构件发布到私有的nexus maven 仓库
  3. 《JS权威指南学习总结--3.8类型转换》
  4. 并发工具类纵览——建立起Java并发体系的大厦
  5. 利用bds和dfs解决 LeetCode 107. Binary Tree Level Order Traversal II
  6. 解放人与设备距离,5G时代的远程操控该如何完成
  7. 苹果折叠屏iPhone不会在明年推出 最快2025年出货
  8. winform 自定义控件属性在属性面板中显示的问题
  9. Django SCRF跨站点请求伪造
  10. CentOS重启与关机
  11. Hdu1208 Pascal's Travels
  12. 管理者的七大失败原因
  13. 结合机械原理的现代少儿编程教育
  14. 港科夜闻|香港科技大学举办北京冬奥精神云分享会,借鉴成功经验延续奥运精神...
  15. esxi虚拟机密码忘了,使用PE工具清楚原来密码
  16. android 灰阶模式,加强系统封闭性,安卓9.0新增几大功能,网友:已经赶上苹果iOS了...
  17. 关于奈奎斯特判据的通俗理解
  18. STM32F4xx实现接入Internet的“基石”——PartA
  19. 草根站长心酸路:你的网站后来怎么样了?
  20. 《8.按键和CPU的中断系统》

热门文章

  1. Ubuntu 12.04 安装配置 Apache2
  2. 区分内边距与外边距padding和margin
  3. 解析应用结构,优化网络效能
  4. 编程行业高手级别必学C语言,要挣大钱必学C语言,要做黑客、红客必学C语言,要面试名企、外企、高薪职位必学C语言。
  5. 首次曝光的计算模型!对标阿里?有没有想过你的中台只是废纸?
  6. 今天的离离原上草的飞鸽传书
  7. 女程序员 一直从事着软件研发的工作
  8. MFC返回的临时对象指针成因?
  9. Windows下C语言网络编程快速入门
  10. 学习Enroll例程