├── .gitignore ├── README.md ├── generate-ddl-hibernate ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── geowarin │ │ ├── GenerateDdlApp.java │ │ ├── HibernateExporter.java │ │ └── model │ │ ├── Article.java │ │ ├── BaseEntity.java │ │ ├── Group.java │ │ ├── Role.java │ │ ├── Tag.java │ │ └── User.java │ └── resources │ └── log4j.properties ├── hibernate-jpa-standalone-dbunit ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── geowarin │ │ │ └── hibernate │ │ │ └── jpa │ │ │ └── standalone │ │ │ ├── App.java │ │ │ └── model │ │ │ └── User.java │ └── resources │ │ ├── META-INF │ │ └── persistence.xml │ │ ├── log4j.properties │ │ └── sql │ │ └── import-users.sql │ └── test │ ├── java │ └── com │ │ └── geowarin │ │ └── hibernate │ │ └── jpa │ │ └── standalone │ │ ├── AbstractDbUnitJpaTest.java │ │ └── AppTest.java │ └── resources │ ├── META-INF │ └── persistence.xml │ └── test-data.xml └── standalone-data-jpa ├── README.md ├── pom.xml └── src ├── config └── com │ └── geowarin │ └── standalonedatajpa │ └── config │ └── StandaloneDataJpaConfig.java ├── main ├── java │ └── com │ │ └── geowarin │ │ └── standalonedatajpa │ │ ├── MainBean.java │ │ ├── StandaloneDataJpaApp.java │ │ ├── model │ │ └── User.java │ │ └── repository │ │ └── UserRepository.java └── resources │ ├── log4j.properties │ └── sql │ ├── import-users.sql │ └── schema.sql └── test └── java └── com └── geowarin └── standalonedatajpa └── repository ├── UserRepositoryTest.java ├── afterInsert.xml └── userAdminData.xml /.gitignore: -------------------------------------------------------------------------------- 1 | .settings/ 2 | .classpath 3 | .project 4 | target/ 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Hibernate examples 2 | ================== 3 | 4 | Hibernate examples from my blog http://geowarin.wordpress.com/tag/hibernate -------------------------------------------------------------------------------- /generate-ddl-hibernate/README.md: -------------------------------------------------------------------------------- 1 | Generate DDL with hibernate configuration 2 | ========================================= 3 | 4 | A little trick to generate DDL using hibernate. 5 | 6 | See my blog : http://geowarin.wordpress.com/2013/01/21/generate-ddl-with-hibernate -------------------------------------------------------------------------------- /generate-ddl-hibernate/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.geowarin 5 | generate-ddl-hibernate 6 | 7 | jar 8 | 1.0-SNAPSHOT 9 | 10 | generate-ddl-hibernate 11 | http://geowarin.wordpress.com/ 12 | A simple project to generate DDL with hibernate 13 | 14 | 15 | UTF-8 16 | 1.7 17 | 1.7 18 | 4.1.5.Final 19 | 20 | 21 | 22 | 23 | org.hibernate 24 | hibernate-core 25 | ${hibernate.version} 26 | 27 | 28 | org.reflections 29 | reflections 30 | 0.9.8 31 | 32 | 33 | org.slf4j 34 | slf4j-log4j12 35 | 1.7.2 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/GenerateDdlApp.java: -------------------------------------------------------------------------------- 1 | package com.geowarin; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class GenerateDdlApp { 7 | 8 | public static void main(String[] args) throws IOException { 9 | 10 | // HibernateExporter exporter = new HibernateExporter("org.hibernate.dialect.HSQLDialect", "com.geowarin.model"); 11 | HibernateExporter exporter = new HibernateExporter("org.hibernate.dialect.MySQL5Dialect", "com.geowarin.model"); 12 | exporter.setGenerateDropQueries(true); 13 | exporter.exportToConsole(); 14 | exporter.export(new File("schema.sql")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/HibernateExporter.java: -------------------------------------------------------------------------------- 1 | package com.geowarin; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.OutputStream; 7 | import java.io.PrintWriter; 8 | 9 | import javax.persistence.Entity; 10 | import javax.persistence.MappedSuperclass; 11 | 12 | import org.hibernate.cfg.AvailableSettings; 13 | import org.hibernate.cfg.Configuration; 14 | import org.hibernate.dialect.Dialect; 15 | import org.hibernate.engine.jdbc.internal.FormatStyle; 16 | import org.hibernate.engine.jdbc.internal.Formatter; 17 | import org.reflections.Reflections; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | 21 | /** 22 | * This class will create an hibernate {@link Configuration} with the given dialect and will scan provided 23 | * package for {@link MappedSuperclass} and {@link Entity}. 24 | * You can then use the export methods to generate your schema DDL. 25 | * 26 | * @author Geoffroy Warin (https://github.com/geowarin) 27 | * 28 | */ 29 | public class HibernateExporter { 30 | 31 | private static Logger log = LoggerFactory.getLogger(HibernateExporter.class); 32 | 33 | private String dialect; 34 | private String entityPackage; 35 | 36 | private boolean generateCreateQueries = true; 37 | private boolean generateDropQueries = false; 38 | 39 | private Configuration hibernateConfiguration; 40 | 41 | public HibernateExporter(String dialect, String entityPackage) { 42 | this.dialect = dialect; 43 | this.entityPackage = entityPackage; 44 | 45 | hibernateConfiguration = createHibernateConfig(); 46 | } 47 | 48 | public void export(OutputStream out, boolean generateCreateQueries, boolean generateDropQueries) { 49 | 50 | Dialect hibDialect = Dialect.getDialect(hibernateConfiguration.getProperties()); 51 | try (PrintWriter writer = new PrintWriter(out)) { 52 | 53 | if (generateCreateQueries) { 54 | String[] createSQL = hibernateConfiguration.generateSchemaCreationScript(hibDialect); 55 | write(writer, createSQL, FormatStyle.DDL.getFormatter()); 56 | } 57 | if (generateDropQueries) { 58 | String[] dropSQL = hibernateConfiguration.generateDropSchemaScript(hibDialect); 59 | write(writer, dropSQL, FormatStyle.DDL.getFormatter()); 60 | } 61 | } 62 | } 63 | 64 | public void export(File exportFile) throws FileNotFoundException { 65 | 66 | export(new FileOutputStream(exportFile), generateCreateQueries, generateDropQueries); 67 | } 68 | 69 | public void exportToConsole() { 70 | 71 | export(System.out, generateCreateQueries, generateDropQueries); 72 | } 73 | 74 | private void write(PrintWriter writer, String[] lines, Formatter formatter) { 75 | 76 | for (String string : lines) 77 | writer.println(formatter.format(string) + ";"); 78 | } 79 | 80 | private Configuration createHibernateConfig() { 81 | 82 | hibernateConfiguration = new Configuration(); 83 | 84 | final Reflections reflections = new Reflections(entityPackage); 85 | for (Class cl : reflections.getTypesAnnotatedWith(MappedSuperclass.class)) { 86 | hibernateConfiguration.addAnnotatedClass(cl); 87 | log.info("Mapped = " + cl.getName()); 88 | } 89 | for (Class cl : reflections.getTypesAnnotatedWith(Entity.class)) { 90 | hibernateConfiguration.addAnnotatedClass(cl); 91 | log.info("Mapped = " + cl.getName()); 92 | } 93 | hibernateConfiguration.setProperty(AvailableSettings.DIALECT, dialect); 94 | return hibernateConfiguration; 95 | } 96 | 97 | public boolean isGenerateDropQueries() { 98 | return generateDropQueries; 99 | } 100 | 101 | public void setGenerateDropQueries(boolean generateDropQueries) { 102 | this.generateDropQueries = generateDropQueries; 103 | } 104 | 105 | public Configuration getHibernateConfiguration() { 106 | return hibernateConfiguration; 107 | } 108 | 109 | public void setHibernateConfiguration(Configuration hibernateConfiguration) { 110 | this.hibernateConfiguration = hibernateConfiguration; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/Article.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.JoinTable; 9 | import javax.persistence.Lob; 10 | import javax.persistence.ManyToMany; 11 | import javax.persistence.Table; 12 | 13 | import org.hibernate.annotations.Cache; 14 | import org.hibernate.annotations.CacheConcurrencyStrategy; 15 | 16 | import com.google.common.base.Objects; 17 | 18 | @Entity 19 | @Table(name = "articles") 20 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 21 | public class Article extends BaseEntity { 22 | 23 | @Column(name = "title", nullable = false) 24 | private String title; 25 | 26 | @Column(name = "text_id", nullable = true) 27 | private String textId; 28 | 29 | @Column(name = "html_contents", nullable = false) 30 | @Lob 31 | private String htmlContents; 32 | 33 | @ManyToMany 34 | @JoinTable(name="articles_tags", 35 | joinColumns= 36 | @JoinColumn(name="article_id", referencedColumnName="id"), 37 | inverseJoinColumns= 38 | @JoinColumn(name="tag_id", referencedColumnName="id") 39 | ) 40 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 41 | public Set tags; 42 | 43 | public String getTitle() { 44 | return title; 45 | } 46 | 47 | public void setTitle(String title) { 48 | this.title = title; 49 | } 50 | 51 | public String getTextId() { 52 | return textId; 53 | } 54 | 55 | public void setTextId(String textId) { 56 | this.textId = textId; 57 | } 58 | 59 | public String getHtmlContents() { 60 | return htmlContents; 61 | } 62 | 63 | public void setHtmlContents(String htmlContents) { 64 | this.htmlContents = htmlContents; 65 | } 66 | 67 | public Set getTags() { 68 | return tags; 69 | } 70 | 71 | public void setTags(Set tags) { 72 | this.tags = tags; 73 | } 74 | 75 | @Override 76 | public String toString() { 77 | return Objects.toStringHelper(this) 78 | .add("title", title) 79 | .add("htmlContents", htmlContents) 80 | .add("tags", tags) 81 | .add("textId", textId) 82 | .toString(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | 4 | import java.util.Date; 5 | 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.MappedSuperclass; 10 | import javax.persistence.PrePersist; 11 | import javax.persistence.PreUpdate; 12 | import javax.persistence.Temporal; 13 | import javax.persistence.TemporalType; 14 | import javax.persistence.Version; 15 | 16 | import com.google.common.base.Objects; 17 | 18 | 19 | /** 20 | * @author Geoffroy Warin (https://github.com/geowarin) 21 | * 22 | */ 23 | @MappedSuperclass 24 | public abstract class BaseEntity { 25 | 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.AUTO) 28 | private Long id; 29 | 30 | @Temporal(TemporalType.DATE) 31 | private Date createdOn; 32 | 33 | @Temporal(TemporalType.DATE) 34 | private Date modifiedOn; 35 | 36 | @Version 37 | private long version = 0; 38 | 39 | public Long getId() { 40 | return id; 41 | } 42 | 43 | public void setId(Long id) { 44 | this.id = id; 45 | } 46 | 47 | public Date getCreatedOn() { 48 | return createdOn; 49 | } 50 | 51 | public void setCreatedOn(Date createdOn) { 52 | this.createdOn = createdOn; 53 | } 54 | 55 | public Date getModifiedOn() { 56 | return modifiedOn; 57 | } 58 | 59 | public void setModifiedOn(Date modifiedOn) { 60 | this.modifiedOn = modifiedOn; 61 | } 62 | 63 | public long getVersion() { 64 | return version; 65 | } 66 | 67 | public void setVersion(long version) { 68 | this.version = version; 69 | } 70 | 71 | @PrePersist 72 | public void initTimeStamps() { 73 | if (createdOn == null) { 74 | createdOn = new Date(); 75 | } 76 | modifiedOn = createdOn; 77 | } 78 | 79 | @PreUpdate 80 | public void updateTimeStamp() { 81 | modifiedOn = new Date(); 82 | } 83 | 84 | @Override 85 | public String toString() { 86 | return Objects.toStringHelper(this).add("id", id).toString(); 87 | } 88 | 89 | @Override 90 | public int hashCode() { 91 | return Objects.hashCode(id); 92 | } 93 | 94 | @Override 95 | public boolean equals(Object obj) { 96 | if (this == obj) 97 | return true; 98 | if (obj == null) 99 | return false; 100 | if (getClass() != obj.getClass()) 101 | return false; 102 | 103 | BaseEntity other = (BaseEntity) obj; 104 | return Objects.equal(this.getId(), other.getId()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/Group.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.OneToMany; 9 | import javax.persistence.Table; 10 | 11 | import org.hibernate.annotations.Cache; 12 | import org.hibernate.annotations.CacheConcurrencyStrategy; 13 | 14 | import com.google.common.base.Objects; 15 | 16 | @Entity 17 | @Table(name = "groups") 18 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 19 | public class Group extends BaseEntity { 20 | 21 | @Column(name = "name", nullable = false, length = 50) 22 | private String name; 23 | 24 | @OneToMany 25 | @JoinColumn(name="group_id") 26 | private Set roles; 27 | 28 | public Group() { 29 | } 30 | 31 | public String getName() { 32 | return name; 33 | } 34 | 35 | public void setName(String name) { 36 | this.name = name; 37 | } 38 | 39 | public Set getRoles() { 40 | return roles; 41 | } 42 | 43 | public void setRoles(Set roles) { 44 | this.roles = roles; 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return Objects.toStringHelper(this) 50 | .add("name", name) 51 | .add("roles", roles) 52 | .toString(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Table; 6 | 7 | import org.hibernate.annotations.Cache; 8 | import org.hibernate.annotations.CacheConcurrencyStrategy; 9 | 10 | import com.google.common.base.Objects; 11 | 12 | @Entity 13 | @Table(name = "roles") 14 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 15 | public class Role extends BaseEntity { 16 | 17 | @Column(name = "name", nullable=false, length=50) 18 | private String name; 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return Objects.toStringHelper(this) 31 | .add("name", name) 32 | .toString(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/Tag.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.ManyToMany; 8 | import javax.persistence.Table; 9 | import javax.xml.bind.annotation.XmlTransient; 10 | 11 | import org.hibernate.Hibernate; 12 | import org.hibernate.annotations.Cache; 13 | import org.hibernate.annotations.CacheConcurrencyStrategy; 14 | 15 | import com.google.common.base.Objects; 16 | import com.google.common.base.Objects.ToStringHelper; 17 | 18 | /** 19 | * An entity which models a tag. 20 | * 21 | * @author gwarin 22 | */ 23 | @Entity 24 | @Table(name = "tags") 25 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 26 | public class Tag extends BaseEntity { 27 | 28 | @Column(name = "name", nullable = false) 29 | private String name; 30 | 31 | @ManyToMany(mappedBy = "tags") 32 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 33 | private Set
articles; 34 | 35 | public Tag() { 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | @XmlTransient 47 | public Set
getArticles() { 48 | return articles; 49 | } 50 | 51 | public void setArticles(Set
articles) { 52 | this.articles = articles; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | // return LazyToStringHelper.toStringHelper(this) 58 | // .add("name", name) 59 | // .add("articles", articles) 60 | // .toString(); 61 | ToStringHelper helper = Objects.toStringHelper(this) 62 | .add("name", name); 63 | if (Hibernate.isInitialized(articles)) { 64 | helper.add("articles", articles); 65 | } 66 | return helper.toString(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/java/com/geowarin/model/User.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.OneToMany; 9 | import javax.persistence.Table; 10 | 11 | import org.hibernate.annotations.Cache; 12 | import org.hibernate.annotations.CacheConcurrencyStrategy; 13 | 14 | import com.google.common.base.Objects; 15 | 16 | /** 17 | * An entity class which contains the information of a single person. 18 | * 19 | * @author Geoffroy Warin (https://github.com/geowarin) 20 | * 21 | */ 22 | @Entity 23 | @Table(name = "users") 24 | @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 25 | public class User extends BaseEntity { 26 | 27 | @Column(name = "user_name", nullable = false, unique=true, length=50) 28 | private String userName; 29 | 30 | @Column(name = "password", nullable = false, length=80) 31 | private String password; 32 | 33 | @Column(name = "email", nullable = false) 34 | private String email; 35 | 36 | @OneToMany 37 | @JoinColumn(name="user_id") 38 | private Set groups; 39 | 40 | public String getUserName() { 41 | return userName; 42 | } 43 | 44 | public void setUserName(String userName) { 45 | this.userName = userName; 46 | } 47 | 48 | public String getPassword() { 49 | return password; 50 | } 51 | 52 | public void setPassword(String password) { 53 | this.password = password; 54 | } 55 | 56 | public String getEmail() { 57 | return email; 58 | } 59 | 60 | public void setEmail(String email) { 61 | this.email = email; 62 | } 63 | 64 | public Set getGroups() { 65 | return groups; 66 | } 67 | 68 | public void setGroups(Set groups) { 69 | this.groups = groups; 70 | } 71 | 72 | @Override 73 | public String toString() { 74 | return Objects.toStringHelper(this) 75 | .add("userName", userName) 76 | .add("email", email) 77 | .add("groups", groups) 78 | .toString(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /generate-ddl-hibernate/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.appender.Stdout=org.apache.log4j.ConsoleAppender 2 | log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout 3 | log4j.appender.Stdout.layout.conversionPattern=%-5p - %-c - %m\n 4 | 5 | log4j.rootLogger=INFO,Stdout 6 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/README.md: -------------------------------------------------------------------------------- 1 | Simple JPA Hibernate Standalone with dbUnit tests 2 | ================================================= 3 | 4 | This is a very simple project using hibernate as a standalone (no server required) JPA provider. 5 | Features simple tests with dbUnit. 6 | 7 | See my blog : http://geowarin.wordpress.com/2013/01/20/using-hibernate-as-a-jpa-provider-in-a-java-se-environment-and-run-tests-with-dbunit/ -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.geowarin 6 | hibernate-jpa-standalone-dbunit 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | simple-hibernate-jpa-standalone 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 1.6 16 | 1.6 17 | 1.2.16 18 | 1.6.1 19 | 20 | 21 | 22 | 23 | 24 | org.hibernate 25 | hibernate-entitymanager 26 | 4.1.5.Final 27 | 28 | 29 | 30 | org.hsqldb 31 | hsqldb 32 | 2.2.9 33 | 34 | 35 | org.slf4j 36 | slf4j-log4j12 37 | 1.7.2 38 | 39 | 40 | 41 | junit 42 | junit 43 | 4.11 44 | test 45 | 46 | 47 | org.dbunit 48 | dbunit 49 | 2.4.9 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/main/java/com/geowarin/hibernate/jpa/standalone/App.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.hibernate.jpa.standalone; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.EntityManagerFactory; 5 | import javax.persistence.Persistence; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import com.geowarin.hibernate.jpa.standalone.model.User; 11 | 12 | /** 13 | * Simple standalone JPA app. 14 | * Will load the user inserted by the script import-users.sql 15 | * 16 | * @author Geoffroy Warin (https://github.com/geowarin) 17 | * 18 | */ 19 | public class App { 20 | 21 | private static Logger log = LoggerFactory.getLogger(App.class); 22 | 23 | public static void main(String[] args) { 24 | 25 | EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence"); 26 | EntityManager entityManager = entityManagerFactory.createEntityManager(); 27 | 28 | User found = entityManager.find(User.class, 1L); 29 | log.info("found=" + found); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/main/java/com/geowarin/hibernate/jpa/standalone/model/User.java: -------------------------------------------------------------------------------- 1 | 2 | package com.geowarin.hibernate.jpa.standalone.model; 3 | 4 | import java.io.Serializable; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.Table; 12 | 13 | @Table(name = "users") 14 | @Entity 15 | public class User implements Serializable { 16 | 17 | private static final long serialVersionUID = 1L; 18 | 19 | @Id 20 | @GeneratedValue(strategy=GenerationType.AUTO) 21 | private long id; 22 | 23 | @Column(name = "name", nullable = false, unique=true, length=50) 24 | private String name; 25 | 26 | public long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return "User [id=" + id + ", name=" + name + "]"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/main/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | org.hibernate.ejb.HibernatePersistence 6 | com.geowarin.hibernate.jpa.standalone.model.User 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.appender.Stdout=org.apache.log4j.ConsoleAppender 2 | log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout 3 | log4j.appender.Stdout.layout.conversionPattern=%-5p - %-c - %m\n 4 | 5 | log4j.rootLogger=INFO,Stdout 6 | log4j.logger.org.hibernate=INFO 7 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/main/resources/sql/import-users.sql: -------------------------------------------------------------------------------- 1 | 2 | INSERT INTO users(id, name) VALUES(1, 'admin'); -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/test/java/com/geowarin/hibernate/jpa/standalone/AbstractDbUnitJpaTest.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.hibernate.jpa.standalone; 2 | 3 | import java.io.InputStream; 4 | import java.sql.SQLException; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityManagerFactory; 8 | import javax.persistence.Persistence; 9 | 10 | import org.dbunit.DatabaseUnitException; 11 | import org.dbunit.database.DatabaseConfig; 12 | import org.dbunit.database.DatabaseConnection; 13 | import org.dbunit.database.IDatabaseConnection; 14 | import org.dbunit.dataset.IDataSet; 15 | import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; 16 | import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory; 17 | import org.dbunit.operation.DatabaseOperation; 18 | import org.hibernate.HibernateException; 19 | import org.hibernate.internal.SessionImpl; 20 | import org.junit.AfterClass; 21 | import org.junit.Before; 22 | import org.junit.BeforeClass; 23 | 24 | /** 25 | * Abstract unit test case class. 26 | * This will load the test-data.xml dataset before each test case and will clean the database before each test 27 | * 28 | * @author Geoffroy Warin (https://github.com/geowarin) 29 | * 30 | */ 31 | public abstract class AbstractDbUnitJpaTest { 32 | 33 | private static EntityManagerFactory entityManagerFactory; 34 | private static IDatabaseConnection connection; 35 | private static IDataSet dataset; 36 | protected static EntityManager entityManager; 37 | 38 | /** 39 | * Will load test-dataset.xml before each test case 40 | * @throws DatabaseUnitException 41 | * @throws HibernateException 42 | */ 43 | @BeforeClass 44 | public static void initEntityManager() throws HibernateException, DatabaseUnitException { 45 | entityManagerFactory = Persistence.createEntityManagerFactory("persistence-test"); 46 | entityManager = entityManagerFactory.createEntityManager(); 47 | connection = new DatabaseConnection(((SessionImpl) (entityManager.getDelegate())).connection()); 48 | connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory()); 49 | 50 | FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder(); 51 | flatXmlDataSetBuilder.setColumnSensing(true); 52 | InputStream dataSet = Thread.currentThread().getContextClassLoader().getResourceAsStream("test-data.xml"); 53 | dataset = flatXmlDataSetBuilder.build(dataSet); 54 | } 55 | 56 | @AfterClass 57 | public static void closeEntityManager() { 58 | entityManager.close(); 59 | entityManagerFactory.close(); 60 | } 61 | 62 | /** 63 | * Will clean the dataBase before each test 64 | * 65 | * @throws SQLException 66 | * @throws DatabaseUnitException 67 | */ 68 | @Before 69 | public void cleanDB() throws DatabaseUnitException, SQLException { 70 | DatabaseOperation.CLEAN_INSERT.execute(connection, dataset); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/test/java/com/geowarin/hibernate/jpa/standalone/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.hibernate.jpa.standalone; 2 | 3 | 4 | import java.util.List; 5 | 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import com.geowarin.hibernate.jpa.standalone.model.User; 10 | 11 | /** 12 | * 13 | * 14 | * @author Geoffroy Warin (https://github.com/geowarin) 15 | * 16 | */ 17 | public class AppTest extends AbstractDbUnitJpaTest { 18 | 19 | @Test 20 | public void testFind() { 21 | 22 | User user = entityManager.find(User.class, 1L); 23 | Assert.assertNotNull(user); 24 | Assert.assertEquals("userTest", user.getName()); 25 | } 26 | 27 | @Test 28 | public void testInsert() { 29 | 30 | User newUser = new User(); 31 | newUser.setName("insert"); 32 | 33 | entityManager.getTransaction().begin(); 34 | 35 | entityManager.persist(newUser); 36 | long id = newUser.getId(); 37 | 38 | entityManager.getTransaction().commit(); 39 | 40 | User user = entityManager.find(User.class, id); 41 | Assert.assertNotNull(user); 42 | Assert.assertEquals("insert", user.getName()); 43 | } 44 | 45 | @Test 46 | public void testFindAll() { 47 | 48 | List allUsers = entityManager.createQuery("from User").getResultList(); 49 | Assert.assertEquals(2, allUsers.size()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/test/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | org.hibernate.ejb.HibernatePersistence 6 | com.geowarin.hibernate.jpa.standalone.model.User 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /hibernate-jpa-standalone-dbunit/src/test/resources/test-data.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /standalone-data-jpa/README.md: -------------------------------------------------------------------------------- 1 | Spring Data JPA standalone - dbUnit tests 2 | ========================================= 3 | 4 | This project demonstrate how to use Spring Data JPA in a Java SE environment and how to test our repositories with dbUnit. 5 | 6 | See my blog for further information : http://geowarin.wordpress.com/2013/01/21/using-spring-data-jpa-in-a-java-se-environment-and-run-tests-with-dbunit 7 | -------------------------------------------------------------------------------- /standalone-data-jpa/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.geowarin 6 | standalone-data-jpa 7 | 8 | jar 9 | 1.0-SNAPSHOT 10 | 11 | standalone-data-jpa 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 1.7 17 | 1.7 18 | 3.2.0.RELEASE 19 | 1.2.0.RELEASE 20 | 4.1.5.Final 21 | 22 | 23 | 24 | 25 | 26 | org.codehaus.mojo 27 | build-helper-maven-plugin 28 | 1.7 29 | 30 | 31 | add-source 32 | generate-sources 33 | 34 | add-source 35 | 36 | 37 | 38 | src/config 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework 50 | spring-context-support 51 | ${spring.version} 52 | 53 | 54 | org.springframework 55 | spring-context 56 | ${spring.version} 57 | 58 | 59 | org.springframework 60 | spring-jdbc 61 | ${spring.version} 62 | 63 | 64 | org.springframework 65 | spring-orm 66 | ${spring.version} 67 | 68 | 69 | org.springframework 70 | spring-tx 71 | ${spring.version} 72 | 73 | 74 | 75 | 76 | org.springframework.data 77 | spring-data-jpa 78 | ${spring.datajpa.version} 79 | 80 | 81 | 82 | org.hibernate 83 | hibernate-core 84 | ${hibernate.version} 85 | 86 | 87 | org.hibernate 88 | hibernate-entitymanager 89 | ${hibernate.version} 90 | 91 | 92 | 93 | org.hsqldb 94 | hsqldb 95 | 2.2.9 96 | 97 | 98 | org.slf4j 99 | slf4j-log4j12 100 | 1.7.2 101 | 102 | 103 | 104 | junit 105 | junit 106 | 4.11 107 | test 108 | 109 | 110 | org.dbunit 111 | dbunit 112 | 2.4.9 113 | test 114 | 115 | 116 | com.github.springtestdbunit 117 | spring-test-dbunit 118 | 1.0.0 119 | test 120 | 121 | 122 | org.springframework 123 | spring-test 124 | ${spring.version} 125 | test 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/config/com/geowarin/standalonedatajpa/config/StandaloneDataJpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.standalonedatajpa.config; 2 | 3 | import javax.persistence.EntityManagerFactory; 4 | import javax.sql.DataSource; 5 | 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 9 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 10 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 11 | import org.springframework.orm.hibernate4.HibernateExceptionTranslator; 12 | import org.springframework.orm.jpa.JpaTransactionManager; 13 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 14 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 15 | import org.springframework.transaction.PlatformTransactionManager; 16 | import org.springframework.transaction.annotation.EnableTransactionManagement; 17 | 18 | import com.geowarin.standalonedatajpa.MainBean; 19 | 20 | @Configuration 21 | @EnableJpaRepositories("com.geowarin.standalonedatajpa.repository") 22 | @EnableTransactionManagement 23 | public class StandaloneDataJpaConfig { 24 | 25 | @Bean 26 | public DataSource dataSource() { 27 | return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) 28 | .addScript("classpath:sql/schema.sql") 29 | .addScript("classpath:sql/import-users.sql") 30 | .build(); 31 | } 32 | 33 | @Bean 34 | public PlatformTransactionManager transactionManager() { 35 | 36 | JpaTransactionManager txManager = new JpaTransactionManager(); 37 | txManager.setEntityManagerFactory(entityManagerFactory()); 38 | return txManager; 39 | } 40 | 41 | @Bean 42 | public HibernateExceptionTranslator hibernateExceptionTranslator() { 43 | return new HibernateExceptionTranslator(); 44 | } 45 | 46 | @Bean 47 | public EntityManagerFactory entityManagerFactory() { 48 | 49 | // will set the provider to 'org.hibernate.ejb.HibernatePersistence' 50 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); 51 | // will set hibernate.show_sql to 'true' 52 | vendorAdapter.setShowSql(true); 53 | // if set to true, will set hibernate.hbm2ddl.auto to 'update' 54 | vendorAdapter.setGenerateDdl(false); 55 | 56 | LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); 57 | factory.setJpaVendorAdapter(vendorAdapter); 58 | factory.setPackagesToScan("com.geowarin.standalonedatajpa.model"); 59 | factory.setDataSource(dataSource()); 60 | 61 | // This will trigger the creation of the entity manager factory 62 | factory.afterPropertiesSet(); 63 | 64 | return factory.getObject(); 65 | } 66 | 67 | @Bean 68 | public MainBean mainBean() { 69 | return new MainBean(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/java/com/geowarin/standalonedatajpa/MainBean.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.standalonedatajpa; 2 | 3 | import java.util.List; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | 9 | import com.geowarin.standalonedatajpa.model.User; 10 | import com.geowarin.standalonedatajpa.repository.UserRepository; 11 | 12 | public class MainBean { 13 | 14 | @Autowired 15 | private UserRepository userRepository; 16 | 17 | private static Logger log = LoggerFactory.getLogger(MainBean.class); 18 | 19 | public void start() { 20 | 21 | // Spring Data JPA CRUD operations are transactionnal by default ! 22 | // http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/#transactions 23 | User newUser = new User(); 24 | newUser.setName("inserted"); 25 | userRepository.save(newUser); 26 | 27 | List all = userRepository.findAll(); 28 | log.info("users=" + all); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/java/com/geowarin/standalonedatajpa/StandaloneDataJpaApp.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.standalonedatajpa; 2 | 3 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 | 5 | /** 6 | * @author Geoffroy Warin (https://github.com/geowarin) 7 | * 8 | */ 9 | public class StandaloneDataJpaApp { 10 | 11 | private static final String CONFIG_PACKAGE = "com.geowarin.standalonedatajpa.config"; 12 | 13 | public static void main(String[] args) { 14 | 15 | try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { 16 | 17 | ctx.scan(CONFIG_PACKAGE); 18 | ctx.refresh(); 19 | 20 | MainBean bean = ctx.getBean(MainBean.class); 21 | bean.start(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/java/com/geowarin/standalonedatajpa/model/User.java: -------------------------------------------------------------------------------- 1 | 2 | package com.geowarin.standalonedatajpa.model; 3 | 4 | import java.io.Serializable; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.Table; 12 | 13 | @Table(name = "users") 14 | @Entity 15 | public class User implements Serializable { 16 | 17 | private static final long serialVersionUID = 1L; 18 | 19 | @Id 20 | @GeneratedValue(strategy=GenerationType.AUTO) 21 | private long id; 22 | 23 | @Column(name = "name", nullable = false, unique=true, length=50) 24 | private String name; 25 | 26 | public long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return "User [id=" + id + ", name=" + name + "]"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/java/com/geowarin/standalonedatajpa/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.standalonedatajpa.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.query.Param; 6 | 7 | import com.geowarin.standalonedatajpa.model.User; 8 | 9 | public interface UserRepository extends JpaRepository { 10 | 11 | // Demonstrate query creation by method name 12 | // http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/#jpa.query-methods.query-creation 13 | User findByName(String name); 14 | 15 | // Demonstrate the use of a simple JPQL query 16 | @Query("from User u where upper(u.name) = upper(:name)") 17 | User findByNameIgnoreCase(@Param("name") String name); 18 | } 19 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.appender.Stdout=org.apache.log4j.ConsoleAppender 2 | log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout 3 | log4j.appender.Stdout.layout.conversionPattern=%-5p - %-c - %m\n 4 | 5 | log4j.rootLogger=INFO,Stdout 6 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/resources/sql/import-users.sql: -------------------------------------------------------------------------------- 1 | 2 | INSERT INTO users(id, name) VALUES(1, 'admin'); -------------------------------------------------------------------------------- /standalone-data-jpa/src/main/resources/sql/schema.sql: -------------------------------------------------------------------------------- 1 | create table users (id bigint generated by default as identity (start with 1), name varchar(50) not null, primary key (id), unique (name)) 2 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/test/java/com/geowarin/standalonedatajpa/repository/UserRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.geowarin.standalonedatajpa.repository; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.test.context.ContextConfiguration; 8 | import org.springframework.test.context.TestExecutionListeners; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; 11 | 12 | import com.geowarin.standalonedatajpa.config.StandaloneDataJpaConfig; 13 | import com.geowarin.standalonedatajpa.model.User; 14 | import com.github.springtestdbunit.DbUnitTestExecutionListener; 15 | import com.github.springtestdbunit.annotation.DatabaseSetup; 16 | import com.github.springtestdbunit.annotation.ExpectedDatabase; 17 | 18 | @RunWith(SpringJUnit4ClassRunner.class) 19 | @ContextConfiguration(classes = { StandaloneDataJpaConfig.class }) 20 | @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, 21 | DbUnitTestExecutionListener.class }) 22 | public class UserRepositoryTest { 23 | 24 | @Autowired 25 | private UserRepository userRepository; 26 | 27 | @Test 28 | @DatabaseSetup("userAdminData.xml") 29 | public void testFindAdmin() { 30 | 31 | User admin = userRepository.findOne(1L); 32 | Assert.assertNotNull(admin); 33 | Assert.assertEquals("admin", admin.getName()); 34 | } 35 | 36 | @Test 37 | @DatabaseSetup("userAdminData.xml") 38 | public void testFindByName() { 39 | 40 | User admin = userRepository.findByName("admin"); 41 | Assert.assertNotNull(admin); 42 | Assert.assertEquals("admin", admin.getName()); 43 | } 44 | 45 | @Test 46 | @DatabaseSetup("userAdminData.xml") 47 | public void testFindByNameIgnoreCase() { 48 | 49 | User admin = userRepository.findByNameIgnoreCase("AdMIn"); 50 | Assert.assertNotNull(admin); 51 | Assert.assertEquals("admin", admin.getName()); 52 | } 53 | 54 | @Test 55 | @DatabaseSetup("userAdminData.xml") 56 | @ExpectedDatabase("afterInsert.xml") 57 | public void testInsertUser() { 58 | 59 | User newUser = new User(); 60 | newUser.setName("inserted"); 61 | userRepository.save(newUser); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/test/java/com/geowarin/standalonedatajpa/repository/afterInsert.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /standalone-data-jpa/src/test/java/com/geowarin/standalonedatajpa/repository/userAdminData.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | --------------------------------------------------------------------------------