{"id":3415,"date":"2024-09-19T16:15:31","date_gmt":"2024-09-19T14:15:31","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=3415"},"modified":"2024-09-20T15:09:45","modified_gmt":"2024-09-20T13:09:45","slug":"introduction-to-java-spring-boot-part-iii","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2024\/09\/19\/introduction-to-java-spring-boot-part-iii\/","title":{"rendered":"Introduction to Java Spring Boot (Part III)"},"content":{"rendered":"\n<h4>1. Structure of a Spring Boot Project<\/h4>\n\n\n\n<p>The typical structure of a Spring Boot project looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"756\" height=\"428\" src=\"https:\/\/nguenkam.com\/blog\/wp-content\/uploads\/2024\/09\/image-1.png\" alt=\"\" class=\"wp-image-3417\" srcset=\"https:\/\/nguenkam.com\/blog\/wp-content\/uploads\/2024\/09\/image-1.png 756w, https:\/\/nguenkam.com\/blog\/wp-content\/uploads\/2024\/09\/image-1-300x170.png 300w\" sizes=\"(max-width: 756px) 100vw, 756px\" \/><\/figure>\n\n\n\n<h5>Explanations of the Structure:<\/h5>\n\n\n\n<ul><li><strong>src\/main\/java<\/strong>: This is where all the Java code resides.<\/li><li><strong>com\/example<\/strong>: The base package name, usually reflecting the company&#8217;s domain name.<\/li><li><strong>controller\/<\/strong>: Contains the REST controllers that handle HTTP requests.<\/li><li><strong>service\/<\/strong>: Business logic is implemented here.<\/li><li><strong>repository\/<\/strong>: Data access objects that interact with the database.<\/li><li><strong>Application.java<\/strong>: The main application class that contains the <code>main<\/code> method and starts Spring Boot.<\/li><li><strong>src\/main\/resources<\/strong>: This is where resources like configuration files and static files are located.<\/li><li><strong>application.properties<\/strong>: Configuration file for Spring Boot.<\/li><li><strong>static\/<\/strong>: Static resources like CSS, JS, and images.<\/li><li><strong>templates\/<\/strong>: Templates for rendering views (e.g., Thymeleaf).<\/li><li><strong>src\/test\/java<\/strong>: This is where the tests for the application are located.<\/li><li><strong>pom.xml<\/strong>: Maven project file that defines dependencies and plugins.<\/li><\/ul>\n\n\n\n<h4>2. AOP Concepts (Aspect-Oriented Programming)<\/h4>\n\n\n\n<p>AOP allows you to separate cross-cutting concerns like logging, transactions, and security from business logic. Important terms include:<\/p>\n\n\n\n<ul><li><strong>Aspect<\/strong>: A modular unit of cross-cutting logic.<\/li><li><strong>Join Point<\/strong>: A specific point in the program flow where an aspect can be applied.<\/li><li><strong>Advice<\/strong>: The code that is executed at a Join Point.<\/li><li><strong>Pointcut<\/strong>: An expression that defines the Join Points where Advice is applied.<\/li><\/ul>\n\n\n\n<h5>Example:<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.springframework.stereotype.Component;\n\n@Aspect\n@Component\npublic class LoggingAspect {\n\n    @Before(\"execution(* com.example.service.*.*(..))\")\n    public void logBeforeMethod() {\n        System.out.println(\"A method is being called.\");\n    }\n}<\/code><\/pre>\n\n\n\n<h4>3. Database Access in Spring Boot<\/h4>\n\n\n\n<h5>JDBC Template Example<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\nimport java.util.Map;\n\n@Repository\npublic class UserRepository {\n\n    @Autowired\n    private JdbcTemplate jdbcTemplate;\n\n    public Map&lt;String, Object&gt; getUserById(int id) {\n        String sql = \"SELECT * FROM users WHERE id = ?\";\n        return jdbcTemplate.queryForMap(sql, id);\n    }\n\n    public List&lt;Map&lt;String, Object&gt;&gt; getAllUsers() {\n        String sql = \"SELECT * FROM users\";\n        return jdbcTemplate.queryForList(sql);\n    }\n}<\/code><\/pre>\n\n\n\n<h5>Difference between <code>queryForMap<\/code> and <code>queryForList<\/code><\/h5>\n\n\n\n<ul><li><strong><code>queryForMap<\/code><\/strong>: Returns a single row as a <code>Map<\/code>, using column names as keys.<\/li><li><strong><code>queryForList<\/code><\/strong>: Returns a list of rows, with each row represented as a <code>Map<\/code>.<\/li><\/ul>\n\n\n\n<p><code>JdbcTemplate<\/code> supports batch processing, which allows us to execute multiple SQL statements in a single batch. This can significantly improve performance when inserting or updating large amounts of<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public void batchAddUsers(List&lt;User&gt; users) {\n    String sql = \"INSERT INTO users (name, email) VALUES (?, ?)\";\n    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {\n        @Override\n        public void setValues(PreparedStatement ps, int i) throws SQLException {\n            ps.setString(1, users.get(i).getName());\n            ps.setString(2, users.get(i).getEmail());\n        }\n\n        @Override\n        public int getBatchSize() {\n            return users.size();\n        }\n    });\n}\n<\/code><\/pre>\n\n\n\n<p>To convert rows of the result set into custom objects, we can implement the <code>RowMapper<\/code> interface. This is especially useful for queries that return multiple rows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public List&lt;User&gt; getAllUsers() {\n    String sql = \"SELECT * FROM users\";\n    return jdbcTemplate.query(sql, new UserRowMapper());\n}\n<\/code><\/pre>\n\n\n\n<p>When performing multiple operations that need to be executed as a single unit of work, we can manage transactions using Spring&#8217;s <code>@Transactional<\/code> annotation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Transactional\npublic void createUserAndProfile(User user, Profile profile) {\n    addUser(user.getName(), user.getEmail());\n    \/\/ Insert profile logic here\n}\n<\/code><\/pre>\n\n\n\n<h4>4. Spring Data JDBC<\/h4>\n\n\n\n<p>Spring Data JDBC is a part of the Spring Data project that provides a simplified way to access relational databases using plain JDBC. It focuses on a more straightforward approach to data access by leveraging the concepts of repositories and entities, while maintaining a close relationship with the underlying database.<\/p>\n\n\n\n<h5>Key Features of Spring Data JDBC:<\/h5>\n\n\n\n<ol><li><strong>Entity Mapping<\/strong>: Maps Java objects directly to database tables without the complexity of ORM (Object-Relational Mapping).<\/li><li><strong>Repository Support<\/strong>: Provides a repository abstraction, allowing you to perform CRUD operations without writing boilerplate code.<\/li><li><strong>Simplicity<\/strong>: Offers a simpler programming model compared to JPA, making it easier to understand and use for straightforward use cases.<\/li><\/ol>\n\n\n\n<p>Here&#8217;s a simple example of using Spring Data JDBC:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.data.annotation.Id;\nimport org.springframework.data.jdbc.core.mapping.Table;\nimport org.springframework.data.repository.CrudRepository;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n@Table(\"users\")\npublic class User {\n    @Id\n    private Long id;\n    private String name;\n    private String email;\n\n    \/\/ Getters and Setters\n}\n\n@Repository\npublic interface UserRepository extends CrudRepository&lt;User, Long&gt; {\n    List&lt;User&gt; findByName(String name);\n}\n<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul><li>The&nbsp;<code>User<\/code>&nbsp;class represents a table in the database, with fields mapped to columns.<\/li><li>The&nbsp;<code>UserRepository<\/code>&nbsp;interface extends&nbsp;<code>CrudRepository<\/code>, providing methods to perform CRUD operations without additional implementation.<\/li><\/ul>\n\n\n\n<h4>5. Spring Data JPA<\/h4>\n\n\n\n<h5>What is JPA?<\/h5>\n\n\n\n<p>Java Persistence API (JPA) is a specification for managing relational data in Java applications. Spring Data JPA simplifies the implementation of JPA-based repositories.<\/p>\n\n\n\n<h5>Concrete Example<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface UserRepository extends JpaRepository&lt;User, Integer&gt; {\n    List&lt;User&gt; findByLastName(String lastName);\n}<\/code><\/pre>\n\n\n\n<h5>Dynamic Finder Methods (supported keywords)<\/h5>\n\n\n\n<ul><li><code>findBy<\/code>: Searches by a specific attribute.<\/li><li><code>findByFirstNameAndLastName<\/code>: Searches by multiple attributes.<\/li><li><code>findByAgeGreaterThan<\/code>: Searches for values greater than a specific value.<\/li><\/ul>\n\n\n\n<h5>Advantages of JPA<\/h5>\n\n\n\n<ul><li><strong>Simplicity<\/strong>: Less boilerplate code compared to JDBC.<\/li><li><strong>Abstraction<\/strong>: Hides the complexity of database interaction.<\/li><li><strong>Flexibility<\/strong>: Supports different databases without changes to the code.<\/li><\/ul>\n\n\n\n<h4>5. Comparison: JDBC, JdbcTemplate, and JPA<\/h4>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><thead><tr><th>Feature<\/th><th>JDBC<\/th><th>JdbcTemplate<\/th><th>JPA<\/th><\/tr><\/thead><tbody><tr><td><strong>Level of Abstraction<\/strong><\/td><td>Low (direct database interaction)<\/td><td>Medium (simplifies JDBC operations)<\/td><td>High (object-oriented data access)<\/td><\/tr><tr><td><strong>Ease of Use<\/strong><\/td><td>Requires boilerplate code for CRUD<\/td><td>Reduces boilerplate with utility methods<\/td><td>Uses annotations and repositories for simplicity<\/td><\/tr><tr><td><strong>Error Handling<\/strong><\/td><td>Manual exception handling<\/td><td>Automatic translation to Spring exceptions<\/td><td>Automatic handling of persistence exceptions<\/td><\/tr><tr><td><strong>Transaction Management<\/strong><\/td><td>Manual management required<\/td><td>Supports transaction management with Spring<\/td><td>Built-in transaction handling with&nbsp;<code>@Transactional<\/code><\/td><\/tr><tr><td><strong>Performance<\/strong><\/td><td>High (direct access)<\/td><td>High (optimized for batch operations)<\/td><td>Generally lower due to additional overhead of ORM<\/td><\/tr><tr><td><strong>Mapping<\/strong><\/td><td>Manual mapping of result sets to objects<\/td><td>Supports&nbsp;<code>RowMapper<\/code>&nbsp;for custom mapping<\/td><td>Automatic mapping of entities to database tables<\/td><\/tr><tr><td><strong>Use Cases<\/strong><\/td><td>Suitable for simple, performance-critical applications<\/td><td>Good for straightforward JDBC operations<\/td><td>Best for complex applications requiring rich domain models<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h5>Fazit<\/h5>\n\n\n\n<ul><li><strong>JDBC<\/strong>&nbsp;is suitable for low-level database access where performance is critical, but it requires a lot of boilerplate code.<\/li><li><strong>JdbcTemplate<\/strong>&nbsp;simplifies JDBC usage by handling resource management and providing utility methods, making it easier to work with databases.<\/li><li><strong>JPA<\/strong>&nbsp;is ideal for applications that require complex object-relational mapping and a higher level of abstraction, but it comes with additional overhead.<\/li><\/ul>\n\n\n\n<p>Choosing between these options depends on the specific requirements of our application, including complexity, performance, and ease of use.<\/p>\n\n\n\n<h4>6. Transactions in Spring<\/h4>\n\n\n\n<p>Spring provides support for declarative transactions, allowing us to manage transactions through annotations.<\/p>\n\n\n\n<h5>Example of Transactions<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\n@Service\npublic class UserService {\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Transactional\n    public void createUser(User user) {\n        userRepository.save(user);\n        \/\/ Additional operations that are part of the transaction\n    }\n}<\/code><\/pre>\n\n\n\n<h5>Conclusion<\/h5>\n\n\n\n<p>This tutorial gives us an overview of the structure of a Spring Boot project, AOP, database access, Spring Data JPA, and transactions. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Structure of a Spring Boot Project The typical structure of a Spring Boot project looks like this: Explanations of the Structure: src\/main\/java: This is where all the Java code resides. com\/example: The base package name, usually reflecting the company&#8217;s domain name. controller\/: Contains the REST controllers that handle HTTP requests. service\/: Business logic is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3403,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[554,868],"tags":[893,889,891,890,892,894],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3415"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=3415"}],"version-history":[{"count":4,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3415\/revisions"}],"predecessor-version":[{"id":3426,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3415\/revisions\/3426"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/3403"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=3415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=3415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=3415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}