📜 ⬆️ ⬇️

Spring + Hibernate for beginners

Instead of a disclaimer


On Habré there are already many articles on the topic of working with Hibernate, however, as it seemed to me, they are all quite complex for beginners. This article is aimed at explaining the basics of working with ORM and will be useful primarily for those who are just starting to develop their own applications and have little experience with databases in general, and with tools like Hibernate in particular. Mature developers are unlikely to find in the article for themselves something new; all the rest please under the cat.

What is ORM?


No modern web application can do without storing a huge amount of different information. This task is usually assigned to special programs - the Database Management System for the DBMS. According to the scheme of organizing the database are divided into several types, and so it happened that the most common type turned out to be relational.

In relational databases, data is organized in the form of essentials (tables) and links between them. Programmers working with object-oriented programming languages ​​often face the challenge of transforming data from a form that the DBMS understands into the usual object form. Almost always the solution of these problems takes a huge amount of time and makes you write such constructs:

public ArrayList<BookBean> getBooksByGenreId (int genre_id) { ArrayList<BookBean> result = new ArrayList<>(); try { int i = 1; String query = "SELECT * FROM books " + "LEFT JOIN genres2books " + "ON genres2books.book_id=books.id " + "WHERE genre_id=? AND books.approved = 1 " + "ORDER BY user_rating DESC LIMIT 250"; connection = getConnection(); ps = connection.prepareStatement(query); ps.setInt(i++, genre_id); resultSet = ps.executeQuery(); while (resultSet.next()) { String name = resultSet.getString("name"); String summary = resultSet.getString("summary"); String cover_url = resultSet.getString("cover_url"); String cover_min_url = resultSet.getString("cover_min_url"); String example = resultSet.getString("example"); String isbn = resultSet.getString("isbn"); String foreign_id = resultSet.getString("foreign_id"); double rev_rating = resultSet.getDouble("rev_rating"); double usr_rating = resultSet.getDouble("user_rating"); int user_id = resultSet.getInt("user_id"); int id = resultSet.getInt("id"); int approved = resultSet.getInt("approved"); int top = resultSet.getInt("top"); int partner_id = resultSet.getInt("partner_id"); long sum_mark = resultSet.getLong("sum_mark"); long votes_num = resultSet.getLong("votes_num"); result.add( new BookBean(id, name, summary, cover_url, cover_min_url, example, rev_rating, usr_rating, user_id, top, approved, sum_mark, votes_num, isbn, foreign_id, partner_id) ); } } catch (SQLException | IllegalArgumentException e) { e.printStackTrace(); } finally { try { if (ps!=null) ps.close(); if (connection!=null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } return result; } 

')
And this is only one SELECT, and in fact it is also necessary to organize the correct connection to the DBMS and ensure the normal simultaneous work of several users.

To make life easier for programmers and free us from routine, the technology is called O bject- R elational M apping (ORM), which is implemented by the popular Hibernate library. Hibernate takes on the task of converting data from its relational view into an object, for reading, and from an object into a relational view - for writing. In addition, the library allows you to easily set up a connection to the DBMS and with its help it is very easy to manage transactions.

Fast start


Now we will try using Hibernate to create a map to the object form of such a table, which is used to store sessions:

image

Create a Bean SessionBean. A bean is a class that has a constructor without parameters, a constructor with all parameters, and get and set methods for all fields are defined.

 @Entity //,      @Table(name = "sessions") //      public class SessionBean implements Serializable{ @Column(name = "username") //    private String username; //   @Id //  ,     ID        @Column(name = "series") private String series; @Column(name = "token") private String token; @Column(name = "last_used") private Timestamp lastUsed; public SessionBean() {} public SessionBean(String username, String series, String token, Timestamp lastUsed) { this.username = username; this.series = series; this.token = token; this.lastUsed = lastUsed; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Timestamp getLastUsed() { return lastUsed; } public void setLastUsed(Timestamp last_used) { this.lastUsed = last_used; } } 


We will also create a DAO (Data Access Object) - a special class that will provide us with read and write operations to the database.

 public class NEXEntityDAO<Bean> { protected final Class<Bean> typeParameterClass; public NEXEntityDAO(Class<Bean> typeParameterClass) { this.typeParameterClass = typeParameterClass; } @Override public void delete(int id) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Bean del = (Bean) session.get(typeParameterClass, id); session.delete(del); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } } @Override public ArrayList<Bean> getAll() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); String hql = String.format("from %s",typeParameterClass.getCanonicalName()); Query SQLQuery = session.createQuery(hql); ArrayList<Bean> result = (ArrayList<Bean>) SQLQuery.list(); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } return result; } public Bean getById(int id) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Bean result = (Bean) session.get(typeParameterClass, id); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } return result; } @Override public void update(Bean object) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.update(object); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } } @Override public void add(Bean object) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(object); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } } @Deprecated public void clear() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); String hql = String.format("delete from %s",typeParameterClass.getCanonicalName()); Query query = session.createQuery(hql); query.executeUpdate(); session.getTransaction().commit(); if (session.isOpen()) { session.close(); } } } 


After that, it becomes very easy to retrieve, edit and add data to the database.

  NEXEntityDAO<SessionBean> sessionDAO = new NEXEntityDAO<>(SessionBean.class); SessionBean session = sessionDAO.getById(5) //    = 5 ArrayList<SessionBean> allSessions = sessionDAO.getAll(); //    session.setToken(“21313”); sessionDAO.update(session); //   SessionBean adding = new SessionBean(“st”,”ri”,”ng”,ts); sessionDAO.add(adding); //   


On it we will finish acquaintance with ORM. In the following articles we will consider the most interesting subtleties of working with this technology, as well as techniques for testing databases.

Source: https://habr.com/ru/post/255829/


All Articles