JPA + Hibernate + PostgreSQL + Maven基本配置示例
JPA + Hibernate + PostgreSQL工程示例。
注意 user 在 postgresql 中为保留关键字,所以如果你persist一个名为User的类的时候就会报语法错误。
创建项目
<dependencies> <!-- JPA --> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.0.1.Final</version> </dependency> <!-- log4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <!-- JDBC Driver --> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> </dependencies>
配置persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" 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"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <!-- standard properties --> <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/jpa-test" /> <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" /> <property name="javax.persistence.jdbc.user" value="postgres" /> <property name="javax.persistence.jdbc.password" value="111111" /> <!-- hibernate-specific properties --> <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>
注:
创建User实体bean
@Entity @Table(name = "USER_") public class User { @Id @GeneratedValue private long id; private String name; private String password; // getters and setters ... }
前面提到User是postgresql的保留字,所以我们使用 USER_ 作为表名,以防冲突。
编写主函数
public static void main(String[] args) { // obtain factory EntityManagerFactory emf = Persistence.createEntityManagerFactory("test"); // obtain EntityManager EntityManager em = emf.createEntityManager(); // start transaction em.getTransaction().begin(); User u = new User(); u.setName("bruce"); em.persist(u); em.getTransaction().commit(); }
然后执行主类即可。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。