Permalink
Browse files

first commit

  • Loading branch information...
0 parents commit fdc81f7202e2e54096e5506e9506cfda30556f91 @alexec committed May 13, 2012
63 pom.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" 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>hibernate-jpa</groupId>
+ <artifactId>hibernate-jpa</artifactId>
+ <version>1.0</version>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.derby</groupId>
+ <artifactId>derby</artifactId>
+ <version>10.4.1.3</version>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-entitymanager</artifactId>
+ <version>3.6.9.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate.javax.persistence</groupId>
+ <artifactId>hibernate-jpa-2.0-api</artifactId>
+ <version>1.0.0.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.10</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>catalina</artifactId>
+ <version>6.0.18</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <finalName>tutorial</finalName>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>tomcat-maven-plugin</artifactId>
+ <version>1.1</version>
+ <configuration>
+ <server>localhost</server>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <packaging>war</packaging>
+</project>
30 src/main/java/tutorial/Role.java
@@ -0,0 +1,30 @@
+package tutorial;
+
+import javax.persistence.*;
+
+@Entity
+public class Role {
+ @Id // @Id indicates that this it a unique primary key
+ @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server
+ private Long id;
+
+ @Column(length = 32, unique = true)
+ // the optional @Column allows us makes sure that the name is limited to a suitable size and is unique
+ private String name;
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+}
43 src/main/java/tutorial/User.java
@@ -0,0 +1,43 @@
+package tutorial;
+
+import javax.persistence.*;
+import java.util.HashSet;
+import java.util.Set;
+
+@Entity
+@Table(name = "usr") // @Table is optional, but "user" is a keyword in many SQL variants
+@NamedQuery(name = "User.findByName", query = "select u from User u where u.name = :name")
+public class User {
+ @Id // @Id indicates that this it a unique primary key
+ @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server
+ private Long id;
+
+ @Column(length = 32, unique = true)
+ // the optional @Column allows us makes sure that the name is limited to a suitable size and is unique
+ private String name;
+
+ // note that no setter for ID is provided, Hibernate will generate the ID for us
+
+ public long getId() {
+ return id;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @ManyToMany
+ private final Set<Role> roles = new HashSet<Role>();
+
+ public boolean addRole(Role role) {
+ return roles.add(role);
+ }
+
+ public Set<Role> getRoles() {
+ return roles;
+ }
+}
25 src/main/resources/META-INF/persistence.xml
@@ -0,0 +1,25 @@
+<?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="tutorialPU" transaction-type="RESOURCE_LOCAL">
+ <provider>org.hibernate.ejb.HibernatePersistence</provider>
+ <!-- the JNDI data source -->
+ <non-jta-data-source>java:comp/env/jdbc/tutorialDS</non-jta-data-source>
+ <properties>
+ <!-- if this is true, hibernate will print (to stdout) the SQL it executes,
+ so you can check it to ensure it's not doing anything crazy -->
+ <property name="hibernate.show_sql" value="true" />
+ <property name="hibernate.format_sql" value="true" />
+ <!-- since most database servers have slightly different versions of the
+ SQL, Hibernate needs you to choose a dialect so it knows the subtleties of
+ talking to that server -->
+ <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
+ <!-- this tell Hibernate to update the DDL when it starts, very useful
+ for development, dangerous in production -->
+ <property name="hibernate.hbm2ddl.auto" value="update" />
+ </properties>
+ </persistence-unit>
+</persistence>
10 src/main/webapp/WEB-INF/index.jsp
@@ -0,0 +1,10 @@
+<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
+ pageEncoding="ISO-8859-1"%>
+<html>
+<head>
+<title>Hello World!</title>
+</head>
+<body>
+ <p>Hello World!</p>
+</body>
+</html>
9 src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="2.5"
+ xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+ <display-name>Tutorial</display-name>
+ <welcome-file-list>
+ <welcome-file>/index.jsp</welcome-file>
+ </welcome-file-list>
+</web-app>
39 src/test/java/tutorial/AbstractTest.java
@@ -0,0 +1,39 @@
+package tutorial;
+
+import org.apache.derby.jdbc.EmbeddedDataSource;
+import org.apache.naming.java.javaURLContextFactory;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+public abstract class AbstractTest {
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ System.setProperty(Context.INITIAL_CONTEXT_FACTORY, javaURLContextFactory.class.getName());
+ System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
+ InitialContext ic = new InitialContext();
+
+ ic.createSubcontext("java:");
+ ic.createSubcontext("java:comp");
+ ic.createSubcontext("java:comp/env");
+ ic.createSubcontext("java:comp/env/jdbc");
+
+ EmbeddedDataSource ds = new EmbeddedDataSource();
+ ds.setDatabaseName("tutorialDB");
+ // tell Derby to create the database if it does not already exist
+ ds.setCreateDatabase("create");
+
+ ic.bind("java:comp/env/jdbc/tutorialDS", ds);
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+
+ InitialContext ic = new InitialContext();
+
+ ic.unbind("java:comp/env/jdbc/tutorialDS");
+ }
+}
179 src/test/java/tutorial/UserTest.java
@@ -0,0 +1,179 @@
+package tutorial;
+
+import org.hibernate.LazyInitializationException;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import java.util.Date;
+
+import static org.junit.Assert.assertEquals;
+
+public class UserTest extends AbstractTest {
+ @Test
+ public void testNewUser() {
+
+ EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ entityManager.getTransaction().begin();
+
+ User user = new User();
+
+ user.setName(Long.toString(new Date().getTime()));
+
+ entityManager.persist(user);
+
+ entityManager.getTransaction().commit();
+
+ // see that the ID of the user was set by Hibernate
+ System.out.println("user=" + user + ", user.id=" + user.getId());
+
+ User foundUser = entityManager.find(User.class, user.getId());
+
+ // note that foundUser is the same instance as user and is a concrete
+ // class (not a JDX proxy)
+ System.out.println("foundUser=" + foundUser);
+
+ assertEquals(user.getName(), foundUser.getName());
+
+ entityManager.close();
+ }
+
+ @Test(expected = Exception.class)
+ public void testNewUserWithTxn() throws Exception {
+
+ EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ entityManager.getTransaction().begin();
+ try {
+ User user = new User();
+
+ user.setName(Long.toString(new Date().getTime()));
+
+ entityManager.persist(user);
+
+ if (true) { throw new Exception(); }
+
+ entityManager.getTransaction().commit();
+ } catch (Exception e) {
+ entityManager.getTransaction().rollback();
+ throw e;
+ }
+
+ entityManager.close();
+ }
+
+ @Test
+ public void testNewUserAndAddRole() {
+
+ EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ entityManager.getTransaction().begin();
+
+ User user = new User();
+
+ user.setName(Long.toString(new Date().getTime()));
+
+ Role role = new Role();
+
+ role.setName(Long.toString(new Date().getTime()));
+
+ entityManager.persist(user);
+ entityManager.persist(role);
+
+ entityManager.getTransaction().commit();
+
+ assertEquals(0, user.getRoles().size());
+
+ entityManager.getTransaction().begin();
+
+ user.addRole(role);
+
+ entityManager.merge(user);
+
+ entityManager.getTransaction().commit();
+
+ assertEquals(1, user.getRoles().size());
+
+ entityManager.close();
+ }
+
+ @Test
+ public void testFindUser() throws Exception {
+
+ EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ entityManager.getTransaction().begin();
+
+ User user = new User();
+
+ String name = Long.toString(new Date().getTime());
+
+ user.setName(name);
+
+ Role role = new Role();
+
+ role.setName(name);
+
+ user.addRole(role);
+
+ entityManager.persist(role);
+ entityManager.persist(user);
+
+ entityManager.getTransaction().commit();
+
+ entityManager.close();
+
+ entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ User foundUser = entityManager.createNamedQuery("User.findByName", User.class).setParameter("name", name)
+ .getSingleResult();
+
+ System.out.println(foundUser);
+
+ assertEquals(name, foundUser.getName());
+
+ assertEquals(1, foundUser.getRoles().size());
+
+ System.out.println(foundUser.getRoles().getClass());
+
+ entityManager.close();
+ }
+
+ @Test(expected = LazyInitializationException.class)
+ public void testFindUser1() throws Exception {
+
+ EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ entityManager.getTransaction().begin();
+
+ User user = new User();
+
+ String name = Long.toString(new Date().getTime());
+
+ user.setName(name);
+
+ Role role = new Role();
+
+ role.setName(name);
+
+ user.addRole(role);
+
+ entityManager.persist(role);
+ entityManager.persist(user);
+
+ entityManager.getTransaction().commit();
+
+ entityManager.close();
+
+ entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
+
+ User foundUser = entityManager.createNamedQuery("User.findByName", User.class).setParameter("name", name)
+ .getSingleResult();
+
+ entityManager.close();
+
+ assertEquals(1, foundUser.getRoles().size());
+
+ }
+}

0 comments on commit fdc81f7

Please sign in to comment.