JPA的学习和理解
1.jpa和hibernate的关系
jpa:对象关系映射规范
jpa是规范,hibernate是实现,都是为了解决传统jdbc操作复杂,开发效率低而提供的操作数据库的框架
2.jpa和jdbc的区别
jdbc:
本质:处理Java对象和关系型数据库表之间的转换
优点:操作数据库最底层,性能可控
缺点:开发效率低。移植数据库麻烦,没有提供存储数据的缓存,面向SQL语句操作。
jpa:
本质:处理Java对象和关系型数据库表之间的转换,只是对JDBC再次做了一层封装
优点:操作简便,面向持久对象操作,提供缓存(一级缓存、二级缓存、查询缓存),数据库移植性强(数据库方言确定)
缺点:不能干预SQL语句的生成,上亿数据量,不适用jpa,运行效率相对于jdbc更低
3.jpa的配置和CRUD
1.pom.xml配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itsource</groupId>
<artifactId>jpa-demo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>jpaday01</module>
</modules>
<dependencies>
<!-- hibernate的包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- hibernate对于jpa的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- mysql的驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- junit的测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<finalName>pss</finalName>
<plugins>
<plugin>
<!-- Maven的编译插件-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
注意事项:
hibernate的核心包与hibernate对jpa的支持包需要版本一致
2.persistence.xml配置
<persistence 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"
version="2.0">
<persistence-unit name="cn.itsource.jpa" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- 必须配置4个连接数据库属性 -->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />