So, I´m currently on project where I have to create my own repositories without extending Jpa or CRUD repositories, i would like to know how I can implement the same method found in JpaRepository called "findByUsername" to work the same way. It receives a String and returns the whole Object in case it finds the username in the DB.
This is my UserDao
public interface UserDAO extends AbstractDAO<User, Long>{
User findByUsername (String username);
}
And this is my This is my UserDaoImplements there I need to implement the body of the method findByUsername:
@Repository
public class UserDAOImpl extends AbstractDAOImpl<User, Long> implements UserDAO {
@Override
public User findByUsername(String username) {
return null;
}
}
CodePudding user response:
As you have annotated your question with hibernate, I am suggesting to use EntityManager :
public class UserDAOImpl extends AbstractDAOImpl<User, Long> implements UserDAO {
@Autowired
EntityManager em;
@Override
public User findByUsername(String username) {
Query q = em.createNativeQuery("select * from User where username = :username", User.class);
q.setParameter("username", username);
return (User)q.getSingleResult();
}
}