JPA(Hibernate)サンプルコード環境
プロジェクト作成
依存ライブラリの追加
リソースフォルダの作成
JPAの設定
<?xml version="1.0" encoding="UTF-8" ?> <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_1_0.xsd" version="1.0"> <persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> <property name="hibernate.connection.url" value="jdbc:postgresql://my-db-server/mydb01" /> <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /> <property name="hibernate.connection.username" value="db_user" /> <property name="hibernate.connection.password" value="db_passwd" /> <property name="hibernate.show_sql" value="true" /> </properties> </persistence-unit> </persistence> サンプルコードエンティティクラスsrc/main/java/jpa_sample/app01/entity/T1.java package jpa_sample.app01.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "T1") public class T1 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 255, unique = false) private String name; public T1() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 利用クラスsrc/test/java/jpa_sample/app01/Main.java package jpa_sample.app01; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import jpa_sample.app01.entity.T1; public class Main { public static void main(String[] args) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("my-persistence-unit"); EntityManager em = emf.createEntityManager(); String sql = "from T1 where name = ?"; T1 t1 = (T1) em.createQuery(sql).setParameter(1, "taro") .getSingleResult(); System.out.println("### RESULT: " + t1); } } 参考http://trasis.jp/blog/lab/2008/09/hibernate-jpa%E7%92%B0%E5%A2%83%E6%A7%8B%E7%AF%89.html |
|