I am using the spring mvc3 in my applicatio,and in the dao layer I want to use jdbctemplate,however I do not know where to add the dao,in the controller?
For example:
#Controller
public class UserController{
private UserDao udao;
public String list(Model model){
udao=new UserDaoImple();
List<User> users=udao.list();
model.addAttrubut('users',users);
return "list";
}
}
The above code is just an example,I want to know where to create the userdao?
Also,since I want to use the jdbctemplate,and it is recommended that the jdbctemplate is created only once for one datasourece,so how to make all the daos use the same jdbctemplate?
You could use Spring IOC (dependency injection) to inject the DAO like this
#Autowired
UserDao userdao;
or you could use the repository pattern, and create a central point for all the DAOs so you just go to the repository and ask for the DAO you need.
for that you would have to create singleton class that has all instances of all DAOs and when asked give give an instance to your class, so you don't need to instantiate the Dao just do a
Repo.getUserDaoInstance();
In my opinion, go for the Spring approach you will learn a very useful skill and it's a lot easier to maintain when you know what you are doing.
Related
In my spring boot project, I am using this starter jpa . i have done all the db related thing in appliction.properties. Project is working fine . I fail to undestand where is this methods defination. We have just defined a abstract method how is this method even working?
public interface UserRepository extends JpaRepository<UserEntity, Integer>{
Optional<UserEntity> getUserByUserName(String user);
}
This is part of the magic of JPA Repositories. I don't actually know the details of how it works either, I just know how to use it.
Ultimately, I think it has to do with how Spring proxies interfaces. Spring will create an instance of an interface at runtime. When the methods are named according to the specs, Spring can generate an appropriate method.
Here is a good article that goes into detail on how you can construct the method names to make the query that you want: https://www.baeldung.com/spring-data-derived-queries.
I am working on a multi-threaded Spring Boot/JPA/Hibernate project started by someone else. They have created 10 DAO classes and each one looks something like this:
#Repository
public class FirstDAO
{
#PersistenceContext
private EntityManager entityManager;
...
}
I am working on learning JPA & Hibernate, so I know the entity managers can persist different versions of the same data.
When we have that many DAO classes, are there other pitfalls we need to worry about? Thx!
Edit:
Since I am pretty new with JPA and multi-threading, I am mostly just nervous.
But a question I have is: if you want more than one #Repository for a database then do you have to create an interface that has the #PersistenceContext and then you implement the interface multiple times?
#Repository
public interface userRepository extends JpaRepository<User, Long> {
}
There are many sites showing this way of creating DAO in Spring 4 using JpaRepository. #Repository also creating instance just like #Component, #Service etc. Container internally beans by using new operator while component scan (using #Component scan annotation) of classes having annotation #Component, #Service etc. Then how container create instance for #Repository as shown above, as it is an interface which is purely abstract and we can't create instance for interface using new operator.
Spring will create a SimpleJpaRepository instance for declared Interfaces that extend JpaRepository.
Note: there is much more magic going on. You can add your own queries via #Query to the interface and Repositories also support transaction management. To achieve that the Repository will be wrapped in a proxy which can intercept and dynamically implement its methods.
Is it possible to write my own function implementation along usage of spring repositories?
I would like to actually implement the function
getUserByFirstName()
and not get it automagically.
While i still want to get
getUserById()
automagically from spring-data.
1) is it possible?
2) is it possible to achieve logging for all methods spring data automagically generates? (or should i write them manually with
logger.log("entering method ...");
See section 1.3 of the manual for the first requirement:
http://docs.spring.io/spring-data/jpa/docs/1.4.2.RELEASE/reference/html/repositories.html#repositories.single-repository-behaviour
For the second requirement I guess some AOP based solution might work for you well here. See here for example using Spring's AOP support:
logging with AOP in spring?
Yes, you can!!!
There is an amazing feature in Spring data that allows this:
Create an interface with your custom method:
public interface UserRepositoryCustom {
User getUserByFirstName();
}
Make your Spring Data interface extends this new interface, as well as the Spring data crud interface (or JPA, Mongo or whatever spring data interface you're extending):
public interface MySpringDataRepository extends CrudRepository<User, Long>, UserRepositoryCustom {
}
Create a class that implements only your custom interface. The name of the class must be Impl, for instance: UserRepositoryImpl:
public class MySpringDataRepositoryImpl implements UserRepositoryCustom {
public User getUserByFirstName(){
//Your custom implementation
}
}
Now, you only need to inject the Spring data repository in your service and you can use both methods: the spring-data implemented method and your custom implemented method:
#Inject private MySpringDataRepository myRepository;
That's it!!
Look at this section in the documentation:
Spring Data Custom implementations
I have a question about spring + hibernate
I always use hibernate for my develeppoment, I generate images of the tables and the class DAO
then at logic metier I make simple calls to these methods dao ....
for exemple UserDao=new UserDao () then userdao.persist() ...
Now I have intgret spring, and I do not yet understand ..
1
what is the plus made by him knowing that he is also making calls
has dao Service (the writings that manually) it does not generate the
class dao with hibernate
2
is that with spring I would not worry about manage session for
example open session, close session commit() ...
thank you in advance I would like to have an idea Ccool:
At its core, Spring is a dependency injection framework. This means that instead of doing
public class MyService
private MyDao dao;
public MyService() {
dao = new MyDao();
}
}
You can do
public class MyService
private MyDao dao;
#Autowired
public MyService(MyDao dao) {
this.dao = dao;
}
}
And Spring will automatically call the constructor and inject an instance of MyDao. The main benefit is that the code is easily unit-testable.
On top of that, it allows injecting proxies instead of the actual implementations directly. These proxies will indeed handle the transaction management for you, and more (exception translation, security checks, etc.).
So instead of explicitely opening, committing and rollbacking transactions, you would simply annotate a service method with #Transactional, and Spring would open, commit/rollback the transaction. And the transaction context would automatically propagate to the nested service calls.
This short answer is only to give you an idea. To learn more, read about dependency injection, and read the Spring documentation.
Use Spring annotations like #Service for service classes, #Repository for Dao classes and #Controller for action controllers. Use of #Transactional on service class or methods is suffice to carry out transactions.