JPA-环境搭建
1. 用IDEA的DataBase功能连接数据库:
如果出现问题,连接不上,有两种解决方案:1.驱动问题,换MySql for 5.1;2.在数据库路径后面加:“?serverTimezone=GMT”
2. 引入依赖包:
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.4.3.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.2.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13-beta-3</version> <scope>test</scope> </dependency>
3. 在resources源配置文件夹下创建“META-INF/persistence.xml”配置文件:
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <persistence-unit name="jpa" > <properties> <!-- 连接数据库的基本信息 --> <property name="javax.persistence.jdbc.dirver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/yootk"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="123456"/> <!-- 配置 JPA 实现产品的基本属性. 配置 hibernate 的基本属性 --> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
4. 创建po实体类:
@Getter @Setter @Entity @Table(name = "dept", schema = "yootk") public class DeptEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long deptno; private String dname; private String loc; private Date createdate; private Integer num; private Double avgsal;
5. 在测试类进行添加测试:
@Test public void testAdd() { //1.通过一个持久化单元获取一个实体类的管理对象(SessionFactory) EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa"); //2.通过实体类的管理工厂创建一个新的实体类(Session) EntityManager manager = factory.createEntityManager(); //3.实现数据的增加操作,一定要进行事务管理 manager.getTransaction().begin(); //4.实例化po对象,设置相应的数据内容 DeptEntity dept = new DeptEntity() ; dept.setDname("落花部门"); dept.setLoc("流水国度"); dept.setCreatedate(new Date()); dept.setNum(10); dept.setAvgsal(1.1); // 5、进行持久层管理 manager.persist(dept); // 增加成功之后并没有返回值 // 6、更新操作完成之后需要进行事务提交 manager.getTransaction().commit(); // 提交事务 // 7、关闭相应的数据库连接控制 manager.close(); factory.close(); }