📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
What will we develop?
1. Create a Dynamic Web Project in Eclipse IDE
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.
2. Add Jar Dependencies - Important Step
3. Project Structure
4. MySQL Database Setup
CREATE DATABASE 'demo';
5. Create a JPA Entity - User.java
package net.javaguides.hibernate.model; import java.io.Serializable; 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 = "users") public class User implements Serializable { private static final long serialVersionUID = 1 L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "user_name") private String username; @Column(name = "password") private String password; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } 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; } }
@Entity - This annotation specifies that the class is an entity.
@Table - This annotation specifies the table in the database with which this entity is mapped.
@Id - This annotation specifies the primary key of the entity.
@GeneratedValue - This annotation specifies the generation strategies for the values of primary keys.
@Column - The @Column annotation is used to specify the mapping between a basic entity attribute and the database table column.
6. Create a UserDao.java
package net.javaguides.hibernate.dao; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.hibernate.model.User; import net.javaguides.hibernate.util.HibernateUtil; public class UserDao { public void saveUser(User user) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // save the student object session.save(user); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } public boolean validate(String userName, String password) { Transaction transaction = null; User user = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get an user object user = (User) session.createQuery("FROM User U WHERE U.username = :userName").setParameter("userName", userName) .uniqueResult(); if (user != null && user.getPassword().equals(password)) { return true; } // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } return false; } }
7. Hibernate Java-Based Configuration
package net.javaguides.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import net.javaguides.hibernate.model.User;
/**
* Java based configuration
* @author ramesh Fadatare
*
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/demo?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
8. Create a LoginController.java
package net.javaguides.hibernate.web; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.javaguides.hibernate.dao.UserDao; /** * @email Ramesh Fadatare */ @WebServlet("/login") public class LoginController extends HttpServlet { private static final long serialVersionUID = 1 L; private UserDao loginDao; public void init() { loginDao = new UserDao(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("login.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { authenticate(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = request.getParameter("username"); String password = request.getParameter("password"); if (loginDao.validate(username, password)) { RequestDispatcher dispatcher = request.getRequestDispatcher("login-success.jsp"); dispatcher.forward(request, response); } else { throw new Exception("Login not successful.."); } } }
9. Login form - login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container col-md-8 col-md-offset-3" style="overflow: auto"> <h1>Login Form</h1> <form action="<%=request.getContextPath()%>/login" method="post"> <div class="form-group"> <label for="uname">User Name:</label> <input type="text" class="form-control" id="username" placeholder="User Name" name="username" required> </div> <div class="form-group"> <label for="uname">Password:</label> <input type="password" class="form-control" id="password" placeholder="Password" name="password" required> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html>
10. Login success page - login-success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <div align="center"> <h1>You have logined successfully</h1> </div> </body> </html>
I have some troubles when running project javax.persistence.Index[] javax.persistence.Table.indexes()' but I tried everything, ı can't fix.Could you help me ?
ReplyDelete