Spring Boot 2.0 Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

How it works...

As you have probably noticed, we didn't write a single line of SQL, or even mention anything about database connections, building queries, or things like that. The only hint about the fact that we are dealing with the database-backed data in our code is the presence of class and field annotations: @Entity, @Repository, @Id, @GeneratedValue, and @ManyToOne, along with @ManyToMany and @OneToMany. These annotations, which are a part of the JPA, along with the extension of the CrudRepository interface, are our ways of communicating with Spring about the need to map our objects to the appropriate tables and fields in the database and provide us with the programmatic ability to interact with this data.

Let's go through the following annotations:

  • @Entity indicates that the annotated class should be mapped to a database table. The name of the table will be derived from the name of the class, but it can be configured, if needed. It is important to note that every entity class should have a default protected constructor, which is needed for automated instantiation and Hibernate interactions.
  • @Repository indicates that the interface is intended to provide you with the access and manipulation of data for a database. It also serves as an indication to Spring during the component scan that this instance should be created as a bean that will be available for use and injection into other beans in the application.
  • The CrudRepository interface defines the basic common methods to read, create, update, and delete data from a data repository. The extra methods that we will define in our BookRepository extension, public Book findBookByIsbn(String isbn), indicate that Spring JPA should map the call to this method to a SQL query selecting a book by its ISBN field. This is a convention-named mapping that translates the method name into a SQL query. It can be a very powerful ally, allowing you to build queries, such as findByNameIgnoringCase(String name) and others.
  • The @Id and @GeneratedValue annotations provide you with an indication that an annotated field should be mapped to a primary key column in the database and that the value for this field should be generated, instead of being explicitly entered.
  • The @ManyToOne and @ManyToMany annotations define the relational field associations that refer to the data stored in the other tables. In our case, multiple books belong to one author, and many reviewers review multiple books.
  • The mappedBy attribute in the @OneToMay annotation defines a reverse association mapping. It indicates to Hibernate that the mapping source of truth is defined in the Book class, in the author or publisher fields.
For more information about all the vast capabilities of Spring Data, visit http://docs.spring.io/spring-data/data-commons/docs/current/reference/html/ .