ResultSet in Transaction - java

I've got a method which returns me a ResultSet object:
#Repository
public class SomeDAOImpl implements SomeDAO{
#Override
public ResultSet getSomething()
{
...
}
}
And this is how I call that:
#Service
public class SomeServiceImpl implements SomeService{
#Autowired
private SomeDAO someDAO;
#Transactional
#Override
public void doSomething()
{
someDAO.getSomething();
...
}
}
Questions:
Do I have to close ResultSet?
Is it ok to return ResultSet object?

1 Yes you should close a ResultSet.
2 I suggest you to return an Object and not a ResultSet.
Here a draft as should be... Here a tutorial.
#Repository
public class SomeDAOImpl implements SomeDAO{
#Override
public User getSomething(String username){
User user = getJdbcTemplate().queryForObject("SELECT * FROM USER WHERE USERNAME = ?",
new Object[] { username },
new UserMapper()
);
return user;
}
private class UserMapper implements RowMapper<User>{
#Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("ID"));
user.setUsername(rs.getString("USERNAME"));
user.setName(rs.getString("NAME"));
return user;
}
}
}

Related

NullPointerException when Testing Service and DAO class JUnit

I am testing a DAO class using JUnit and I am getting a nullpointerexception which I am not sure why as I am initiating the service class. The following is the test class:
public class RegisterTest {
private UserDaoImpl userservice = new UserDaoImpl();
#Mock
JdbcTemplate jdbcTemplate;
User user;
#Before
public void setUp() {
user = new User();
}
#Test
public void testSetAddress() {
user.setAddress("A");
assertEquals(user.getAddress(), "A");
}
#Test
public void testSetEmail() {
user.setEmail("B");
assertEquals(user.getEmail(), "B");
}
#Test
public void testSetFirstname() {
user.setFirstname("C");
assertEquals(user.getFirstname(), "C");
}
#Test
public void testSetLastname() {
user.setLastname("D");
assertEquals(user.getLastname(), "D");
}
#Test
public void testSetPassword() {
user.setPassword("E");
assertEquals(user.getPassword(), "E");
}
#Test
public void testSetUsername() {
user.setUsername("F");
assertEquals(user.getUsername(), "F");
}
#Test
public void testRegister() {
userservice.register(user);
String username = user.getUsername();
assertEquals(userservice.findByUsername(username), 1);
}
}
The following is the UserDaoImpl
public class UserDaoImpl implements UserDao {
#Autowired
PasswordEncoder passwordEncoder;
#Autowired
DataSource datasource;
#Autowired
JdbcTemplate jdbcTemplate;
public List<User> findByUsername(String username) {
String sql = "select * from users where username='" + username +
"'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users;
}
public int register(User user) {
// If username is unique
String uniqueusername = "select * from users where username='" +
user.getUsername() + "'";
List<User> users = jdbcTemplate.query(uniqueusername, new
UserMapper());
if(users.size() == 0) {
// encode password
String encryptedPassword =
passwordEncoder.encode(user.getPassword());
// Updating database with new user
String sql = "insert into users values(?,?,?,?,?,?)";
return jdbcTemplate.update(sql, new Object[] {
user.getUsername(),
encryptedPassword,
user.getFirstname(),
user.getLastname(),
user.getEmail(),
user.getAddress() });
}
else {
return 0;
}
}
How can I inject the class in the test class? I guess the reason why the nullpointerxeception is because the dao class is not being injected properly in the test class
You should run your test with adequate runner
RunWith(MockitoJunitRunner.class)
public class RegisterTest {
Then you need to inject your mock inside the DAO
#InjectMocks
private UserDaoImpl userservice = new UserDaoImpl();

Spring Jackson serialization by interface

I have two interfaces and one class:
#JsonDeserialize(as = UserEvent.class)
#JsonSerialize(as = EventAttendee.class)
public interface EventAttendee {
Long getId();
void setId(Long id);
User getUser();
void setUser(User user);
UserResponse getUserResponse();
void setUserResponse(UserResponse userResponse);
}
#JsonDeserialize(as = UserEvent.class)
#JsonSerialize(as = UserAttendee.class)
public interface UserAttendee {
Long getId();
void setId(Long id);
Event getEvent();
void setEvent(Event user);
UserResponse getUserResponse();
void setUserResponse(UserResponse userResponse);
}
public class UserEvent extends BaseEntity implements EventAttendee, UserAttendee {
private Event event = new Event();
private User user = new User();
private UserResponse userResponse;
}
I want return different values of UserEvent based on interface I returning from my controller. Like this:
public List<EventAttendee> getEventAttendees(#PathVariable Long eventId) {
}
public List<UserAttendee> getUserEvents(#PathVariable Long userId) {
}
But it taking first implemented interface(in my case EventAttendee) and return it type from BOTH controlers.
How can I return EventAttendee values from one controller, and UserAttendee from another?
Ok, after I posted question I found answer...
I used Views instead of interfaces. There still interfaces in class, but it's serve for other needs now (not for Jackson).
public class Views {
public interface UserResponse {}
public interface Event extends UserResponse {}
public interface User extends UserResponse {}
}
public class UserEvent extends BaseEntity implements EventAttendee, UserAttendee {
#JsonView(Views.User.class)
private Event event = new Event();
#JsonView(Views.Event.class)
private User user = new User();
#JsonView(Views.UserResponse.class)
private UserResponse userResponse;
}
#JsonView(Views.Event.class)
public List<EventAttendee> getEventAttendees(#PathVariable Long eventId) {
}
#JsonView(Views.User.class)
public List<UserAttendee> getUserEvents(#PathVariable Long userId) {
}

Clarify the sequence of events in a Spring MVC ORM web app project

My professor gave a sample Spring MVC ORM project with Hibernate but I can not figure out the sequence of events involved, in particular about the usage of service business object.
This is just a little part of the project, just to make my ideas clearer.
domain:
#Entity
#Table(name = "department")
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long uid;
private String name;
#OneToMany(mappedBy="department",cascade=CascadeType.PERSIST)
private List<Employee> employees = new ArrayList<Employee>();
public Department() {
}
public Department(String name) {
this.name = name;
}
// getters, setters, hashcode() and equals(), toString()...
controller:
#Controller
#RequestMapping("/department")
public class DepartmentController {
#Autowired
#Qualifier("departmentBO")
private DepartmentBO departmentBO;
static final Logger logger = Logger.getLogger(DepartmentController.class);
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String departmentHome(Model model) {
logger.debug("department home() invoked");
List<Department> list = departmentBO.findAllDepartments();
model.addAttribute("list", list);
return "departments";
}
// i'll paste just the first controller ;)
business:
public interface DepartmentBO {
public void delete(long uid);
public List<Department> findAllDepartments();
public Department findByUid(Long uid);
public void save(Department department);
public void update(Department department);
}
business/impl:
#Service
#Transactional
public class DepartmentBoImpl implements DepartmentBO {
#Autowired
private DepartmentDAO departmentDao;
static final Logger logger = Logger.getLogger(DepartmentBoImpl.class);
#Override
public void save(Department department) {
departmentDao.save(department);
}
#Override
public void update(Department department) {
departmentDao.update(department);
}
#Override
public void delete(long uid) {
departmentDao.delete(uid);
}
#Override
public List<Department> findAllDepartments() {
return departmentDao.findAllDepartments();
}
#Override
public Department findByUid(Long uid) throws DataAccessException {
return departmentDao.findByUid(uid);
}
}
dao:
public interface DepartmentDAO {
public void delete(long uid);
public List<Department> findAllDepartments();
public Department findByUid(Long uid);
public void save(Department user);
public void update(Department user);
}
dao/impl:
#Repository
public class DepartmentDAOImplSf implements DepartmentDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void delete(long uid) {
Department department = (Department) sessionFactory.getCurrentSession()
.get(Department.class, uid);
sessionFactory.getCurrentSession().delete(department);
}
#Override
public void save(Department department) {
sessionFactory.getCurrentSession().save(department);
}
#Override
public void update(Department department) {
sessionFactory.getCurrentSession().saveOrUpdate(department);
}
#Override
public List<Department> findAllDepartments() {
List<Department> list = (List<Department>) sessionFactory
.getCurrentSession()
.createQuery("FROM Department").list();
return list;
}
#Override
public Department findByUid(Long uid) {
Department department = (Department) sessionFactory
.getCurrentSession().get(Department.class, uid);
return department;
}
}
I know that the order is: domain model -> controller-> service -> dao ->db, but why use a DepartmentBO? and why DepartmentBoImpl autowired DepartmentDao? Who of them act first? Something that i'm not understanding is messing up my conception of how it works and the sequence of the process..
Thanks for your help ;)
EDIT: "
In few words my question is, what is the sequence of this code? user goes on the /home page that redirect on "departments" page. But what happen before this --> "List list = departmentBO.findAllDepartments();" ?;)
When the departmentBO.findAllDepartments() method is called if you look at the code it invokes the sessionFactory. That is an internal factory class in Hibernate that basically builds a transactional connection to the DB in order to run a query. You are defining the query in the createQuery method and then ultimately executing it with the list() method. These two methods are part of the database session that Hibernate has instantiated.
Departments Page -> departmentBO.findAllDepartments() -> sessionFactory -> createQuery -> list()
Or in pseudo code-ish
Departments Page -> execute findAllDepartments method -> fetch / build a database connection -> define the query -> execute the query -> Return the list!

Add Spring JDBC support based on annotations

I have task to upgrade Map based storage to DB based storage. My project configuration is based on annotations. Could you explain to me which steps should I take to make it happen? And how will change my dao layer code:
public class TicketDao {
Set<Ticket> tickets = new HashSet<>();
public Set<Ticket> getAll() {
return tickets;
}
public void remove(Ticket ticket){
tickets.remove(ticket);
}
public void put(Ticket ticket){
tickets.add(ticket);
}
}
Create db and schema
Configure DataSource and JdbcTemplate. The simpliest configuration:
#Configuration
public class JdbcConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("");
dataSource.setUrl("");
dataSource.setUsername("");
dataSource.setPassword("");
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
Inject JdbcTemplate into dao and use it
public class TicketDao {
public static final String DELETE_QUERY = "delete from Ticket where id = ?";
public static final String INSERT_QUERY = "insert into Ticket values(?, ?)";
public static final String GET_ALL_QUERY = "select * from Tickets";
#Autowired
JdbcTemplate jdbcTemplate;
public Set<Ticket> getAll() {
return new HashSet<>(jdbcTemplate.query(GET_ALL_QUERY, new RowMapper<Ticket>() {
#Override
public Ticket mapRow(ResultSet rs, int rowNum) throws SQLException {
Ticket ticket = new Ticket();
ticket.setId(rs.getString(1));
//other fields mapping
return ticket;
}
}));
}
public void remove(Ticket ticket){
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(DELETE_QUERY);
statement.setString(1, ticket.getId());
return statement;
}
});
}
public void put(Ticket ticket){
Object[] values = {ticket.getId(), ticket.getName()};
int[] types = {Types.VARCHAR, Types.VARCHAR};
jdbcTemplate.update(INSERT_QUERY, values, types);
}
}

can't get data from database using spring-mvc and hibernate

this is my code:
my model class:
#Entity
#Table(name="admin")
public class Admin extends Profile{
public Admin(){}
public Admin(String mail, String name, String lastName, String password, Date birthDate, int gsm){
super(mail, name, lastName, password, birthDate, gsm);
}
}
the DAO class:
#Repository
public class AdminDAO {
private static final Logger logger = LoggerFactory.getLogger(AdminDAO.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#SuppressWarnings("unchecked")
public List<Admin> listAdmins() {
Session session = this.sessionFactory.getCurrentSession();
List<Admin> adminsList = session.createQuery("from Admin").list();
for(Admin a : adminsList){
logger.info("Admin List::"+a);
}
return adminsList;
}
}
my Service class:
#Service
public class AdminService {
#Autowired
private AdminDAO adminDAO;
public void setAdminDAO(AdminDAO adminDAO) {
this.adminDAO = adminDAO;
}
#Transactional
public List<Admin> listAdmins() {
return this.adminDAO.listAdmins();
}
}
when i run my code i get this error message:
java.lang.NullPointerException
at com.journaldev.spring.dao.AdminDAO.listAdmins(AdminDAO.java:38)
i added an admin manually in my database, but it still showing the null pointer exception
what i am doing wrong ??
note: i have another class that works fine, it gets all entities and when the database is empty, it doesn't generate null pointer exception
You missed the #Autowired or the #Inject annotation for the setter method for adminDAO. It has to be
#Autowired
public void setAdminDAO(AdminDAO adminDAO) {
this.adminDAO = adminDAO;
}
You have to annotate all dependencies of your Bean with #Autowired or #Inject.

Categories

Resources