JPA环境的搭建

    xiaoxiao2021-03-26  6

    persistence.xml配置文件: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="JPA-1" transaction-type="RESOURCE_LOCAL"> <!--配置什么ORM产品作为JPA的实现 --> <provider> org.hibernate.ejb.HibernatePersistence</provider> <!--持久化信息 --> <class>com.test.model.Custerm</class> <properties> <!--连接数据库的基本信息 --> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="root" /> <!--配置JPA信息 实际是Hibernate信息 --> <property name="hinernate.format_sql" value="true" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> Custerm.java package com.test.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Table(name="JPA_CUSTERM") @Entity public class Custerm { private Integer id; private String name; private int age; @Column(name="ID") @GeneratedValue(strategy=GenerationType.AUTO) @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } Main.java package com.test.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.test.model.Custerm; public class Main { public static void main(String[] arg){ //1.获取Jpa单元的名称 String persistenceUnitName="JPA-1"; //2.创建EntityManagerfactory EntityManagerFactory emf=Persistence.createEntityManagerFactory(persistenceUnitName); //3创建EntityManager EntityManager em=emf.createEntityManager(); //4.开启事务 EntityTransaction entityTransaction =em.getTransaction(); entityTransaction.begin(); //5.进行持久化操作 Custerm cs=new Custerm(); cs.setAge(12); cs.setName("IT1"); //6.进行保存 em.persist(cs); //7.提交事务 entityTransaction.commit(); //8.关闭EntityManager em.close(); //9.关闭EntityManagerFactory emf.close(); } }
    转载请注明原文地址: https://ju.6miu.com/read-500292.html

    最新回复(0)