Relationship Handling: Hibernate vs JDBC - java

Imagine I have a MySQL database with the 2 tables patient and medicine. I have displayed their columns below.
Patient
idPatient (int) (primary key)
first_name (varchar)
last_name (varchar)
Medicine
idMedicine (int) (primary key)
idPatient (int) (foreign key)
drug_name (varchar)
Please note that Medicine table does have the foriegn key of Patient table.
Now, if I use pure JDBC, I will do the following to create a bean for the Medicine and Patient tables
PatientBean class
public class PatientBean
{
private int idPatient;
private String first_name;
private String last_name;
public void setIdPatient(int idPatient)
{
this.idPatient = idPatient;
}
public int getIdPatient()
{
return idPatient;
}
public void setFirstName(String first_name)
{
this.first_name = first_name;
}
public String getFirstName()
{
return first_name;
}
public void setLastName(String last_name)
{
this.last_name = last_name;
}
public String getLastName()
{
return last_name;
}
}
`MedicineBean` class
public class MedicineBean
{
private int idMedicine;
private int idPatient;
private String drug_name;
public void setIdMedicine(int idMedicine)
{
this.idMedicine = idMedicine;
}
public int getIdMedicine()
{
return idMedicine;
}
public void setIdPatient(int idPatient)
{
this.idPatient = idPatient;
}
public int getIdPatient()
{
return idPatient;
}
public void setDrugName(String drug_name)
{
this.drug_name = drug_name;
}
public String getDrugName()
{
return drug_name;
}
}
However if I reverse engineer my database for hibernate using a tool like NetBeans which will generate the POJO files, mapping etc for Hibernate, I can expect something like below.
PatientBean class
public class PatientBean
{
private int idPatient;
private String first_name;
private String last_name;
private MedicineBean medicineBean;
public void setIdPatient(int idPatient)
{
this.idPatient = idPatient;
}
public int getIdPatient()
{
return idPatient;
}
public void setFirstName(String first_name)
{
this.first_name = first_name;
}
public String getFirstName()
{
return first_name;
}
public void setLastName(String last_name)
{
this.last_name = last_name;
}
public String getLastName()
{
return last_name;
}
public void setMedicineBean(String medicineBean)
{
this.medicineBean = medicineBean;
}
public String getMedicineBean()
{
return medicineBean;
}
}
MedicineBean class
public class MedicineBean
{
private int idMedicine;
private int idPatient;
private String drug_name;
private Set<PatientBean> patients = new HashSet<PatientBean>(0);
public void setIdMedicine(int idMedicine)
{
this.idMedicine = idMedicine;
}
public int getIdMedicine()
{
return idMedicine;
}
public void setIdPatient(int idPatient)
{
this.idPatient = idPatient;
}
public int getIdPatient()
{
return idPatient;
}
public void setDrugName(String drug_name)
{
this.drug_name = drug_name;
}
public String getDrugName()
{
return drug_name;
}
public void setPatients(Set<PatientBean>patients)
{
this.patients = patients;
}
public Set<PatientBean> getPatients()
{
return patients;
}
}
Not only this, Hibernate will also map the relationship type (one to one, one to many, many to one) inside the xml files. However in JDBC we don't care about them at all, they are just foreign keys treated in same way.
So my question is, why is this difference? I believe most of the operations Hibernate does are useless and just using CPU. For an example, trying to retrieve the list of patients in Patient table when we call getAllMedicines() method. In 99% of the case we just need all medicines not the list of patients, if we need that we can make a join and get it!
So what is the reason behind this? Or else should we maintain the same behavior for JDBC too?

I don't think that with hibernate you lose the full control as you are afraid.
The main difference is that hibernate will add an extra layer between your code and jdbc. This layer can be really thin : you have the choice to use jdbc in hibernate at anytime. So you are not losing any control.
The harder part is to understand how hibernate works so that you can use its higher level api and know how hibernate will translate that to jdbc. This is a bit a complex task, because orm mapping is a complex subject. Reading several times the reference documentation, to know exactly what hibernate can do, and what they recommend to do and not do, is a good starting point. The remaining will come from experience using hibernate.
For your example, you say hibernate map relationship, but this is not the case : your reverse-engineering tool did it. You are free to not map a relationship and map instead just the foreign key basic type (like a Long if the id is a number).
As for the loading of stuff. If you wish to always have a #OneToMany loaded, just annotate it with FetchType.EAGER. #*ToMany associations are lazy by default (to avoid loading too many data), but on the other hand, #*ToOne assocation are EAGER by default.
This can be configured at the entity level, making it the default behavior for queries, but can be overloaded for each query.
You see ? You are not losing control, you just need to understand how the hibernate api translate to jdbc.
Apart from bugs, which are fixed when raised to the hibernate team, the performance impact of hibernate is not that much. And in performance critical part of the application, you always have the choice to resort to jdbc, where the hibernate overhead is 0.
What do you gain from using hibernate ? From my experience, refactoring in entity model / database model is much easier, because you change the hibernate mapping, and all the queries generated by hibernate are automatically changed too. You just have to update the custom queries (SQL / HQL / Criteria) that you've hand-written.
From my experience (10 years using hibernate) on a several hundred tables (some of them with more than 10B rows), several terabytes database, i would not want to go back to plain jdbc, which does not mean i don't use it when it is the perfect tool, but it is just like 1 or 2% of the orm code i write.
Hope that helps.
EDIT: and if you are using hibernate with spring, have a look at spring-jdbc which adds a nice layer around jdbc. There, you nearly doesn't need to read the doc: you recognize directly how it will be translated to jdbc, but it brings lots of utility that reduce a lot the boilerplate of using jdbc directly (like exception handling to close Resultset and PreparedStatement, transformation of ResultSet to List of DTO, etc.).
Of course hibernate and spring-jdbc can be used in the same application. They just have to be configured to use the same transaction layer, and care be taken when used in the same tx.

Related

BeanPropertyRowMapper not converting mysql tinyint 1 to boolean true

public class Foo {
private long id;
private String name;
private boolean isBar;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBar() {
return isBar;
}
public void setBar(boolean isBar) {
this.isBar = isBar;
}
}
#Component
public class FooDAO {
private JdbcTemplate jdbcTemplate;
private FooDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Foo> findAll() {
return jdbcTemplate.query( "SELECT * FROM foo", new BeanPropertyRowMapper<>(Foo.class);
}
}
When I setup a custom FooRowMapper and manually call setBar(rs.getBoolean("is_bar")) Foo.isBar is properly getting set to true when db value is 1, but not when using the BeanPropertyRowMapper instead of a custom row mapper.
According to this, BeanPropertyRowMapper should properly convert 1 to true, so why isn't it in my case?
p.s. I already figured out why but thought I'd post it in case it's helpful to anybody. I'm sure it won't take long for someone else to figure it out and post the answer.
I knew this:
Column values are mapped based on matching the column name as obtained from result set meta-data to public setters for the corresponding properties. The names are matched either directly or by transforming a name separating the parts with underscores to the same name using "camel" case.
But got thrown off because my Foo.isBar property had the correct camel case equivalent of my db field name (is_bar), however, my public setter name was incorrect as setBar; the setter should be setIsBar.
After googling I was also thrown off by others wanting to use BeanPropertyRowMapper to convert database values of Y/N to boolean values.
And I also assumed BeanPropertyRowMapper was actually setting the value to false even though it wasn't and the false value simply remained as the default boolean primitive value.
Another solution if for whatever reason setBar instead setIsBar was actually desired would be to use an field alias in the sql select statement like it says in the docs:
To facilitate mapping between columns and fields that don't have matching names, try using column aliases in the SQL statement like "select fname as first_name from customer".

Java Class Misuse - Best Practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm fairly certain that I am not doing something class related correctly.
I am using a class to create a set of variables (like a javascript object sort of maybe but not really).
I am using it as shown bellow (a basic example)
public class myScript {
public static void main(String[] args) {
Client warehouse = new Client();
Contacts warehouseContactsA = new Contacts();
Contacts warehouseContactsB = new Contacts();
warehouse.idno = 1;
warehouse.name = "warehouse";
warehouse.desc = "I don't exist";
warehouseContactsA.client_idno = 1;
warehouseContactsA.email = "emailAAA#place.com"
warehouseContactsB.client_idno = 1;
warehouseContactsB.email = "emailBBB#place.com"
insertIntoDB(warehouse,
warehouseContactsA,
warehouseContactsB);
}
public static void insertIntoDB(Client warehouse,
Contacts warehouseContactsA,
Contacts warehouseContactsB) {
// code to insert into database here
}
private class Client {
int idno;
String name;
String desc;
}
private class Contacts {
int client_idno;
String email;
}
}
Is there any reason to not use classes this way and if so is there a simpler way to store/manage data that doesn't require a class?
Creating inner classes is probably going to create pitfalls for you. When you don't define them as static then they require an implicit reference back to the outer class, which your code doesn't need, it will only get in the way and cause obscure errors. Maybe you're doing this so you can compile only one class and avoid having a build script? Simple build scripts that use gradle are trivial (not like the bad old days when we used ant), so that shouldn't be an issue. It would be better to move your persistent entities out into separate files.
What you're doing with database connections and transactions is not clear. Generally it's bad to try to do each insert in its own transaction, if only because each transaction has overhead and it increases the time the inserts need to run. Typically you'd want to process the inserts in batches.
Mainly, though, if you're writing a script, use a scripting language. Groovy could be a good choice here:
you wouldn't need an outer class for the procedural script part
you can define multiple public classes in one file
Groovy includes a groovy.sql api for simplifying JDBC code.
import java.util.Arrays;
import java.util.List;
public final class WarehouseRepository {
public static void main(String[] args) {
WarehouseRepository repository = new WarehouseRepository();
Client warehouse = new Client(1, "warehouse", "I don't exist");
Contacts warehouseContactsA = new Contacts(1, "emailAAA#place.com");
Contacts warehouseContactsB = new Contacts(1, "emailBBB#place.com");
repository.insertIntoDB(warehouse, Arrays.asList(warehouseContactsA, warehouseContactsB));
}
public void insertIntoDB(Client warehouse, List<Contacts> contacts) {
// code to insert into database here
}
}
final class Client {
private final int id;
private final String name;
private final String desc;
public Client(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc = desc;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
}
final class Contacts {
private final int clientName;
private final String email;
public Contacts(int clientName, String email) {
this.clientName = clientName;
this.email = email;
}
public int getClientName() {
return clientName;
}
public String getEmail() {
return email;
}
}
Some things to notice:
Try to name the classes with their intentions and some Java conventions. For example, a class doing database operations are usually referred as repository
Unless required, make classes and variables final.
Make fields private, and if they are must have, then make them constructor parameters, instead of public or getter/setters.
If there can be multiple contacts associated with client, then it would be great idea to make List<Contact> as field in client.
I would use Map<String,String> for storing attributes.
Where I would store String and ints as Strings and parse them back when they needed.
hope it helps
Yes, that is a good-enough representation.
No, it's not ideal. There are a couple things you can change to improve the situation:
Visibility option 1: make things private with accessors
You can make things more OO-idiomatic by having your "bean" classes (i.e. objects with data storage purpose only, no logic) fields private, and then having public accessors to mask the inner representation:
public class Client {
private int id;
public int getId() { return this.id; }
public void setId(int id) { this.id = id; }
}
Visibility option 2: make your beans immutable
Another option is to make it so that your beans are immutable (so that you can pass them around in a multi-threaded environment nonchalantly) and also guarantee that they are properly initialized and no one writes to them in an illegal state (for example deleting/zeroing the id but not the rest of the data):
public class Client {
public final int id;
public Client(int id) { this.id = id; }
}
Finally, if you have things that may or may not be there (such as description "I don't exist"), I recommend using Optional types, rather than just String types.

Lambda in Java - Could not analyze lambda code

I’ve got an application with Hibernate (JPA) which I am using in combination with Jinq. I’ve got a table which lists entities and I want the user to be able to filter it. In the table there are persons listed.
#Entity
public class Person {
private String firstName;
private String surName;
#Id
private int id;
public Person() {
}
public Person(final String pFirstName, final String pSurName, final int pID) {
firstName = pFirstName;
surName = pSurName;
id = pID;
}
public int getId() {
return id;
}
public void setId(final int pID) {
id = pID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String pFirstName) {
return firstName = pFirstName;
}
public String getSurName() {
return surName;
}
public void setSurName(final String pSurName) {
surName = pSurName;
}
}
I am using JavaFX for this, but this shouldn’t matter. First thing I tried was to filter the persons by their surname. For filtering, I used Jinq in combination with lambda. My filtering code looks like this:
private List<Person> getFilteredPersons(final String pSurName){
JPAJinqStream<Person> stream = streamProvider.streamAll(Person.class);
stream.where(person -> person.getSurName().contains(pSurName));
List<Person> filteredList = stream.toList();
stream.close();
return filteredList;
}
So the object I am operating on is a normal String. I don’t think that my Person class has anything to do with that. My first thought was, that you can’t use the method boolean contains(...) in lambda because when the error showed up, it said:
Caused by: java.lang.IllegalArgumentException: Could not analyze lambda code
So my question is, is it somehow possible to use the contains-method of a String in lambdacode?
Your question has nothing to do with JPA or lambdas, but everything to do with jinq: it simply doesn't support translating String.contains() to a database query. See http://www.jinq.org/docs/queries.html#N65890 for what is supported.

How to create a one-to-many relationship with JDBI SQL object API?

I'm creating a simple REST application with dropwizard using JDBI. The next step is to integrate a new resource that has a one-to-many relationship with another one. Until now I couldn't figure out how to create a method in my DAO that retrieves a single object that holds a list of objects from another table.
The POJO representations would be something like this:
User POJO:
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Account POJO:
public class Account {
private int id;
private String name;
private List<User> users;
public Account(int id, String name, List<User> users) {
this.id = id;
this.name = name;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
The DAO should look something like this
public interface AccountDAO {
#Mapper(AccountMapper.class)
#SqlQuery("SELECT Account.id, Account.name, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
public Account getAccountById(#Bind("id") int id);
}
But when the method has a single object as return value (Account instead of List<Account>) there seems to be no way to access more than one line of the resultSet in the Mapper class. The only solution that comes close I could find is described at https://groups.google.com/d/msg/jdbi/4e4EP-gVwEQ/02CRStgYGtgJ but that one also only returns a Set with a single object which does not seem very elegant. (And can't be properly used by the resouce classes.)
There seems to be a way using a Folder2 in the fluent API. But I don't know how to integrate that properly with dropwizard and I'd rather stick to JDBI's SQL object API as recommended in the dropwizard documentation.
Is there really no way to get a one-to-many mapping using the SQL object API in JDBI? That is such a basic use case for a database that I think I must be missing something.
All help is greatly appreciated,
Tilman
OK, after a lot of searching, I see two ways dealing with this:
The first option is to retrieve an object for each column and merge it in the Java code at the resource (i.e. do the join in the code instead of having it done by the database).
This would result in something like
#GET
#Path("/{accountId}")
public Response getAccount(#PathParam("accountId") Integer accountId) {
Account account = accountDao.getAccount(accountId);
account.setUsers(userDao.getUsersForAccount(accountId));
return Response.ok(account).build();
}
This is feasible for smaller join operations but seems not very elegant to me, as this is something the database is supposed to do. However, I decided to take this path as my application is rather small and I did not want to write a lot of mapper code.
The second option is to write a mapper, that retrieves the result of the join query and maps it to the object like this:
public class AccountMapper implements ResultSetMapper<Account> {
private Account account;
// this mapping method will get called for every row in the result set
public Account map(int index, ResultSet rs, StatementContext ctx) throws SQLException {
// for the first row of the result set, we create the wrapper object
if (index == 0) {
account = new Account(rs.getInt("id"), rs.getString("name"), new LinkedList<User>());
}
// ...and with every line we add one of the joined users
User user = new User(rs.getInt("u_id"), rs.getString("u_name"));
if (user.getId() > 0) {
account.getUsers().add(user);
}
return account;
}
}
The DAO interface will then have a method like this:
public interface AccountDAO {
#Mapper(AccountMapper.class)
#SqlQuery("SELECT Account.id, Account.name, User.id as u_id, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
public List<Account> getAccountById(#Bind("id") int id);
}
Note: Your abstract DAO class will quietly compile if you use a non-collection return type, e.g. public Account getAccountById(...);. However, your mapper will only receive a result set with a single row even if the SQL query would have found multiple rows, which your mapper will happily turn into a single account with a single user. JDBI seems to impose a LIMIT 1 for SELECT queries that have a non-collection return type. It is possible to put concrete methods in your DAO if you declare it as an abstract class, so one option is to wrap up the logic with a public/protected method pair, like so:
public abstract class AccountDAO {
#Mapper(AccountMapper.class)
#SqlQuery("SELECT Account.id, Account.name, User.id as u_id, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
protected abstract List<Account> _getAccountById(#Bind("id") int id);
public Account getAccountById(int id) {
List<Account> accountList = _getAccountById(id);
if (accountList == null || accountList.size() < 1) {
// Log it or report error if needed
return null;
}
// The mapper will have given a reference to the same value for every entry in the list
return accountList.get(accountList.size() - 1);
}
}
This still seems a little cumbersome and low-level to me, as there are usually a lot of joins in working with relational data. I would love to see a better way or having JDBI supporting an abstract operation for this with the SQL object API.
In JDBI v3, you can use #UseRowReducer to achieve this. The row reducer is called on every row of the joined result which you can "accumulate" into a single object. A simple implementation in your case would look like:
public class AccountUserReducer implements LinkedHashMapRowReducer<Integer, Account> {
#Override
public void accumulate(final Map<Integer, Account> map, final RowView rowView) {
final Account account = map.computeIfAbsent(rowView.getColumn("a_id", Integer.class),
id -> rowView.getRow(Account.class));
if (rowView.getColumn("u_id", Integer.class) != null) {
account.addUser(rowView.getRow(User.class));
}
}
}
You can now apply this reducer on a query that returns the join:
#RegisterBeanMapper(value = Account.class, prefix = "a")
#RegisterBeanMapper(value = User.class, prefix = "u")
#SqlQuery("SELECT a.id a_id, a.name a_name, u.id u_id, u.name u_name FROM " +
"Account a LEFT JOIN User u ON u.accountId = a.id WHERE " +
"a.id = :id")
#UseRowReducer(AccountUserReducer.class)
Account getAccount(#Bind("id") int id);
Note that your User and Account row/bean mappers can remain unchanged; they simply know how to map an individual row of the user and account tables respectively. Your Account class will need a method addUser() that is called each time the row reducer is called.
I have a small library which will be very useful to maintain one to many & one to one relationship.
It also provide more feature for default mappers.
https://github.com/Manikandan-K/jdbi-folder
There's an old google groups post where Brian McAllistair (One of the JDBI authors) does this by mapping each joined row to an interim object, then folding the rows into the target object.
See the discussion here. There's test code here.
Personally this seems a little unsatisfying since it means writing an extra DBO object and mapper for the interim structure. Still I think this answer should be included for completeness!

Save List changes with Hibernate

I have an Object named Token. it has id, name, and value. After saving some data to db, I have loaded them into a web page
_____________________________________________
|____name____|____value____|____operation____|
tkn1 10 ×
tkn2 20 ×
the × sign enable me to delete a token from server collection
now. I have added token tkn3 with value 30 and deleted tkn2 so
the table would be:
_____________________________________________
|____name____|____value____|____operation____|
tkn1 10 ×
tkn3 30 ×
With these changes to the collection, how can I reflect them into database
how to determine the records that deleted, and the records that added?
I applied tow solutions:
I have compared -in business logic layer- the old data with the new data
and find the differences between the then send to database two lists, the first contains
the added tokens and the second contains the ids of tokens to be deleted.
I added a flag named status to the object.. when I add the flag is NEW
when I delete I just set flag to DELETE, and in DB layer I iterate over the collection
one by one object and check the flag.. if NEW then add the record, if DELETE , delete it
and if SAVED (no changes) I do no changes to it..
My questions:
Is this way is good to do this task..?
Is there a Pattern to accomplish this task?
Can Hibernate help me to do that?
• Is this way is good to do this task..?
NO
• Is there a Pattern to accomplish this task?
YES
• Can Hibernate help me to do that?
Hibernate provides the solution for such situation using Cascade Attribute for List property
Refer
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/collections.html
http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/
The blow entity should solve your problem.
#Entity
public class MyEntity {
private static enum Status {
NEW,
PERSISTENT,
REMOVED
}
#Id
private Long id;
private String name;
private int value;
#Transient
private Status uiStatus = Status.NEW;
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public Status getUiStatus() {
return this.uiStatus;
}
public int getValue() {
return this.value;
}
#PostLoad
public void onLoad() {
this.uiStatus = Status.PERSISTENT;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUiStatus(Status uiStatus) {
this.uiStatus = uiStatus;
}
public void setValue(int value) {
this.value = value;
}
}

Categories