Data storage is most important part of computer science.For data storage we use many kind of databases. Here many types of databases exists for example no-sql(mongodb),sql(oracle,mysql). For this post I use mysql. Here I use a ORM technology hibernate.ORM is now widely using in OOP related development.
To continue this post please take a look on my previous post Spring MVC step by step with Service and DAO layer-Part3
Here we will use mysql as database and Hibernate for ORM technology. So we need some jar to use these technologies.
We add some dependency to our pom.xml file
*************************************pox.xml***********************************
********************************end***********************************org.hibernate ejb3-persistence 1.0.1.GA org.hibernate hibernate-annotations 3.3.1.GA mysql mysql-connector-java 5.1.29 javax.transaction jta 1.1
We'll use Annotation based configuration. to used hibernate we need to configure a file into our classpath named by hibernate.cfg.xml.We need to create a db spring by using username root and password root
*******************************hibernate.cfg.xml*****************************
********************************end***********************************com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/spring root root 1 org.hibernate.dialect.MySQLDialect org.hibernate.cache.NoCacheProvider false create
<property name="hbm2ddl.auto">update</property>
***You need it to change after first run
Here we configure database connections and hibernate properties.Now we need to build a session factory for hibernate.I create a class in utils folder on java package
**********************************DbUtils.java*******************************
package com.flopcoder.utils; /** * Created by Flop Coder on 6/1/14. */ import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class DbUtils { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new AnnotationConfiguration() .configure() .buildSessionFactory(); } catch (Throwable ert) { System.err.println("Initial SessionFactory creation failed." + ert); throw new ExceptionInInitializerError(ert); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }***********************end*********************************
Because we use annotation based configuration we need to modify our model classes with annotation
******************************User.java************************
package com.flopcoder.model; import javax.persistence.*; /** * Created by Flop Coder on 6/1/14. */ @Entity @Table(name = "users") public class User { @Id @GeneratedValue private Integer id; @Column(name = "name") private String name; @Column(name = "address") private String address; @Column(name = "mobile") private String mobile; @Column(name = "email") private String email; @Column(name = "user_name") private String userName; @Column(name = "password") private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }*******************************End*********************************
Now we need to modify our controller class WelcomeController.java.
*****************************WelcomeController.java*************************
package com.flopcoder.controller; import com.flopcoder.model.User; import com.flopcoder.service.IUserService; import com.flopcoder.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/") public class WelcomeController { @Autowired IUserService userService; @RequestMapping(method = RequestMethod.GET) public String sayHello(ModelMap model) { User user = userService.save(new User()); model.addAttribute("user",userService.getUserById(user.getId())); model.addAttribute("message", "Welcome to learn spring Step By Step with Database access with hibernate. This is part 4."); return "hello"; } }**************************end********************************
By Using @Autowired we autowire this userservice so we need to create a interface IUserService.java
***************************IUserService.java**************************
package com.flopcoder.service; import com.flopcoder.model.User; /** * Created by Flop Coder on 6/2/14. */ public interface IUserService { public User getUserById(Integer id); public User save(User user); }***************************end**********************************
And corresponding implemented class will also change
*******************************UserService.java ********************************
package com.flopcoder.service; import com.flopcoder.dao.IUserDao; import com.flopcoder.dao.UserDao; import com.flopcoder.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by Flop Coder on 6/1/14. */ @Service public class UserService implements IUserService{ @Autowired IUserDao userDao; @Override public User getUserById(Integer id) { return userDao.getUserById(id); } public User save(User user) { user.setName("FlopCoder"); user.setAddress("Bangladesh"); user.setEmail("flopcoder.82@gmail.com"); user.setMobile("01684398208"); user.setPassword("secret"); user.setUserName("flopcoder"); return userDao.save(user); } }*******************************end********************************
and corresponding dao class also changed
******************************IUserDao.java ********************************
package com.flopcoder.dao; import com.flopcoder.model.User; /** * Created by Flop Coder on 6/2/14. */ public interface IUserDao { public User getUserById(Integer id); public User save(User user); }*******************************end********************************
******************************UserDao.java ********************************
package com.flopcoder.dao; import com.flopcoder.model.User; import com.flopcoder.utils.DbUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; /** * Created by Flop Coder on 6/1/14. */ @Repository public class UserDao implements IUserDao{ @Override public User getUserById(Integer id) { User user = read(id); return user; } @Override public User save(User user) { SessionFactory sessionFactory = DbUtils.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Integer id = (Integer) session.save(user); user.setId(id); session.getTransaction().commit(); session.close(); return user; } private static User read(Integer id) { SessionFactory sf = DbUtils.getSessionFactory(); Session session = sf.openSession(); User user = (User) session.get(User.class, id); session.close(); return user; } }*******************************end********************************
Here we just save a data and then retrieve by using its id.Remaining configuration of the project remain unchanged.
Final standing of project structure is like this
Now You can run maven and execute command maven clean package.and then deploy it using a web server.After deploying you need to use a browser and hit http://localhost:8080/ link.you will get result like this image.
Thanks
0 Comments