Is Repository the only way to save entity data on DB? - spring

I'm studying Spring boot, and i have create several entity, my problem now is to retrieve the data from controller to save it on db.
Surfing on the web I have learned that i have to use JPARepositery or CrudRepositery in this way:
An example with User entity
public interface UserRepository extends CrudRepository<User, Integer> {
}
and to save
User user = new User();
userRepository.save(user);
But if I have many entities, Do I need to create a repository for each entity?
I have read about Session, FactorySession and Transaction they are compatible with Spring boot? How it works? and #Transactional tag how it works?
Thanks in advance

Yes, usually you need to create one Repository per Entity. This is also a good practice because you are placing operations and queries related to the same Entity in the same Repository.
Yes, you can obtain a Session and a FactorySession object (Hibernate), but I would advice you against using Hibernate directy. Instead, it is better to use Spring Data or JPA mechanisms to access your database (just as you do using a Repository). The reason is because Hibernate is an implementation of the JPA standard and today we use JPA to access databases (because it masks the exact implementation of the ORM). This way you can later (potentially) replace Hibernate with another JPA implementation (such as EclipseLink) without the need to change your code (in theory). In most projects you will find Hibernate being used, however.
Yes, Transaction is a Spring annotation and an important database transaction mechanism in Spring Boot, too.

Related

Hibernate session factory and repository confusion

So there are two ways to persist an entity:
Using Hibernate's session factory where we get the current session and call save(), get(), update() methods.
Extending JPA's repository interfaces
I have the following questions:
How are these two methods different in the context of using Hibernate. As far as I understand, Hibernate is an implementation of JPA API. So when I say I want to use Hibernate, does it mean that I can use both of the above methods?
What is the preferred way of the two based on convenience, flexibility and optimisation?
JPA repository behind the scenes uses Hibernate or JPA APIs to implement its functionality and tries to "abstract" it or provide convenience methods on top of it. You don't have to use JPA repositories though, and can always switch to the Hibernate or JPA APIs when needed. Think though, if you really gain any benefit by using the Spring Data JPA repository concept.

With Spring Data JPA, under what circumstances should I use EntityManager directly?

Spring Boot Data JPA does an amazing job of generating repositories and abstracting away the managemet of Datasources and EntityManager etc. But sometimes I see code where the EntityManager is included as a field and accessed directly, like in this Dzone example
I don't really understand from that example, when should I include the EntityManager in my class and interact with it directly and when can I just rely on the repository Spring Data JPA autogenerates? Can someone explain?
One good use of EntityManager that I can think of is when you want to get results from a database using complex queries such as join. You can directly query using EntityManager and use ResultTransformer to get into your custom model.

Is it a must to use spring-data-jdbc when using JdbcTemplate?

I am planning to use Spring JdbcTemplate to access my database. Is it a must to use spring-data-jdbc when using JdbcTemplate? The reason I am asking is I don't need "entity"(POJO) for my table in my application. Would it add some overheads if I use spring-data-jdbc?
You can use the JdbcTemplate without Spring Data JDBC without a problem.
JdbcTemplate existed for many years before Spring Data JDBC was conceived.
Spring Data JDBC does involve an overhead.
It extracts data from POJOs, creates queries and transforms the result back to POJOs.
Of course all that takes resources.
If you don't need/benefit from it don't use it.
You can also start with JdbcTemplate and later start using Spring Data JDBC without a problem if the need arises.
JdbcTemplate is part of the spring-jdbc module, so you only need that (and sprint-tx, which includes the DataAccessException hierarchy).
spring-data-jdbc adds support for (not surprisingly) spring-data on top of spring-jdbc. So you don't need it to use JdbcTemplate, the same as you don't need spring-data-jpa to use the JPA EntityManager.
Spring-data-jdbc is implemented on the basis of spring-jdbc. If you don't need Entity at all, then using spring-jdbc to interact directly with the database is the most convenient and flexible. In this case, using spring-data-jdbc is just a pure increase in learning costs. Spring-data-jdbc is designed for DDD (Domain Driven Design) mode, which is different from the current mainstream programming model. The learning cost is not low...

Spring JDBCTemplate and Hibernate

I have a Spring, Spring Data, JPA/Hibernate application.
The legacy part of the application uses JdbcTemplate the new stuff uses spring-data/hibernate and everything is wrapped in a transaction.
Problem is when I modify an entity via hibernate and the legacy part of the system attempts to query something that's been modified I don't get the updated values with out having to explicitly "flush" the entity manager each time.
Is it possible execute the JdbcTemplate queries against hibernate's first-level cache?
What about trying this?
Edit: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/jpa/JpaTransactionManager.html
This transaction manager also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access JPA and services which use plain JDBC (without being aware of JPA)! Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy). Note that this requires a vendor-specific JpaDialect to be configured.

Design question

We are building software in java, and are new to it. I confused about JPA.
Normally in MVC pattern, SQL queries are hidden in model. And controller can't access
the db directly.
When I use JPA, should model retrieve JPA object to controller? If yes, then controller has access to db, and this is against to pattern?
JPA is just an abstraction between your Domain Model Object and SQL (your JPA implementation like Hibernate etc. creates all the SQL queries for you).
The controller will not even know which database JPA uses at all. If you want a simpler application architecture your controller can use the JPA features directly. Other architecture use a Data Acces Object layer (where these objects provide methods like List getAllThingsBetween(Date from, Date to)) between your controller and JPA, so that the controller won't even know, that you are using JPA.

Resources