1) Example on Maven 3 + Spring 4 (Spring MVC) + Hibernate 4.3.5.Final (Annotation) + JPA + MySQL 5.5 + java 8.
Architecture diagram above, is between Spring MVC + Hibernate + JPA + Mysql 5.5
1.1) For this example project , it used Data Access Object Pattern or DAO pattern in Domain layer.
1.2) Based on Architecture diagram above, in JPA box, I used Hibernate ORM to integrate between table database.
- Create table ‘user‘ and table ‘user_details‘, One-To-One Join Table.
CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
);CREATE TABLE `user_details` (
`user_detail_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`address` VARCHAR(255),
`poscode` VARCHAR(10),
PRIMARY KEY (`user_detail_id`),
KEY `user_fk` (`user_id`),
CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
);
open CMD , and your folder project , add this command and Enter :
mvn archetype:generate -DgroupId=<Your domain name> -DartifactId=<Project Name> -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
- My Example: mvn archetype:generate -DgroupId=com.fndong -DartifactId=SpringMVCProjOne -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
- If you check the result is : Build Success , its mean you are successfully create new web app project using maven.
2.) Then , Import the SpringMVCProjOne maven project to your Eclipse Mars.
2.1) after importing , check your Build Path , some folder java are missing “src\main\java” and “src\test\java” , remove the missing , and Add new “Add Folder..” , create the two missing folder.
3) Check your pom.xml, add your dependencies jar files below:
Add Spring 4 + Hibernate 4.3.5.Final dependency in pom.xml.
<properties>
<spring.version>4.0.1.RELEASE</spring.version>
<jdk.version>1.8</jdk.version>
<hib.version>4.3.5.Final</hib.version>
</properties>
<dependencies>
<!– Spring dependencies –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency><!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency><!– Hibernate framework –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version> ${hib.version}</version>
</dependency>
4) Then , check Maven Dependency in Web Deployment Assembly.
5.) For creating an entities , i’ll using generate entities using JPA.
5.1) If you creating an entity ,it doesn’t view the database connection , please make sure you enable JPA . ( for newbies – create JPA Project)
- the libraries in jpaLinkEclise :
5.2.) create package for entity “com.fndong.user.entities“, and add your User table and User_detail table Entity.
5.2.1.) Right-click the SpringMVCProjOne project in the Project Explorer and select NEW > JPA Entities from Tables.
- unchecked the List generate classes in persistence.xml ( Because we will using Spring Autowired )
5.3.) Then , it will automatically generate classes entities User and User_details.
5.4.) User.java entity in “com.fndong.user.entities” :
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
@Entity
@NamedQuery(name=”User.findAll“, query=”SELECT u FROM User u“)
public class User implements Serializable {
private static final long serialVersionUID = 1L;@Id
@Column(name=”user_id“)
private int userId;private String email;
private String name;
private String password;
//bi-directional many-to-one association to UserDetail
@OneToMany(mappedBy=”user“)
private List<UserDetail> userDetails;public User() {
}// getter and Setter …….
5.5.) UserDetail.java entity in “com.fndong.user.entities” :
import java.io.Serializable;
import javax.persistence.*;@Entity
@Table(name=”user_details“)
@NamedQuery(name=”UserDetail.findAll“, query=”SELECT u FROM UserDetail u“)
public class UserDetail implements Serializable {
private static final long serialVersionUID = 1L;@Id
@Column(name=”user_detail_id“)
private int userDetailId;private String address;
private String poscode;
//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name=”user_id“)
private User user;// getter and Setter …….
- JPALink Plugin will automatically set for the tables that have join – one to Many.
@ManyToOne
@JoinColumn(name=”user_id“)
private User user;
- JPA API that we have been use such as :
- @Id annotation
- @Collumn annotation
- @JoinColumn annotation
- @Table annotation
- @NamedQuery annotation
- @Entity annotation
6.0.) Create the DAO Interface and DAO Implementation “com.fndong.user.Dao” :
6.1.) Create User entity DAO Interface in “com.fndong.user.Dao” , NEW > Interface > Name – UserDao > Finish .
package com.fndong.user.dao;
import com.fndong.user.entities.User;
public interface UserDao {
// Get / Search
public User getUserDatabyName(String username);// create
public int create(User user);// edit
public int updateUser(User user);
}
- Dao Interface for User – UserDao.java, i have add Three Functions , 1. Search – getUserDatabyName(String username) 2. Add- Create(User user) , Edit – UpdateUser(User user).
6.2.) Create Dao Implementation where your you will add HQL – Hibernate SQL , This class is responsible to get data from a data source which can be database – UserDaoImpl.java.
- Above diagram is how you can add the interface UserDao for creating Dao Implementation – UserDaoImpl.java.
package com.fndong.user.dao;
import com.fndong.user.entities.User;
public class UserDaoImpl implements UserDao {
/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#getUserDatabyName(java.lang.String)
*/
@Override
public User getUserDatabyName(String username) {
// TODO Auto-generated method stub
return null;
}/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#create(com.fndong.user.entities.User)
*/
@Override
public int create(User user) {
// TODO Auto-generated method stub
return 0;
}/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#updateUser(com.fndong.user.entities.User)
*/
@Override
public int updateUser(User user) {
// TODO Auto-generated method stub
return 0;
}
- Above Dao Implemention automatically created method from Dao Interface.
7.) Lets creating Hibernate.cfg.xml in package – /src/main/resources (Hibernate ORM Mapping database – Annotation )
<?xml version=”1.0” encoding=”UTF-8“?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN“
“http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd“>
<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class“>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.password“>P@ssw0rd</property>
<property name=”hibernate.connection.url“>jdbc:mysql://localhost:3306/hibernate</property>
<property name=”hibernate.connection.username“>root</property>
<property name=”hibernate.dialect“>org.hibernate.dialect.MySQLDialect</property>
<property name=”cache.provider_class“>org.hibernate.cache.NoCacheProvider</property>
<property name=”show_sql“>true</property>
<property name=”hbm2ddl.auto“>validate</property><mapping class=”com.fndong.user.entities.User“/>
<mapping class=”com.fndong.user.entities.UserDetails“/>
</session-factory>
</hibernate-configuration>
8.) Create Hibernate SessionFactory class – HibernateUtil.java in new package “com.fndong.util“.
package com.fndong.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();@SuppressWarnings(“deprecation“)
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration()
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
9. Create Service layer …. to be continued