hibernate
Hibernate
DAO
- UserDao.java
package cz.isn.example.dao; import cz.isn.example.model.User; import java.util.List; /** * * @author Jiří Blažek <jiri.blazek@isn.cz> */ public interface UserDao { public List<User> findAll(); public User findById(long id); public void saveUser(User user); public void updateUser(User user); publid void deleteUser(User user); }
- UserDaoImpl.java
package cz.isn.example.dao; import cz.isn.example.model.User; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @author Jiří Blažek <jiri.blazek@isn.cz> */ @Component("userDao") public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; @Override public List<User> findAll() { List<User> users = sessionFactory.getCurrentSession() .createQuery("from User u") .list(); if (!users.isEmpty()) { return users; } else { return null; } } @Override public User findById(long id) { List<User> users = sessionFactory.getCurrentSession() .createQuery("from User u where u.id = :id") .setLong("id", id) .list(); if (!user.isEmpty()) { return users.get(0); } else { return null; } } @Override public void saveUser(User user) { sessionFactory.getCurrentSession().save(user); } @Override public void updateUser(User user) { sessionFactory.getCurrentSession().update(user); } @Override public void deleteUser(User user) { sessionFactory.getCurrentSession().delete(user); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return this.sessionFactory; } }
hibernate.txt · Poslední úprava: 2023/12/26 19:13 autor: 127.0.0.1