Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to persist API

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use Java to persist API, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

For application developers, Java persistence APIJava Persistence API (JPA) is an important java feature that needs to be thoroughly understood. It defines for Java developers how to convert method calls to objects into scenarios for accessing, persisting, and managing data stored in NoSQL and relational databases.

This article examines JPA in detail through a tutorial example of building a bicycle loan service. This example uses the Spring Boot framework, MongoDB database (no longer open source), and Maven package management to build a large application and a create, read, update, and delete (CRUD) layer. Here I choose NetBeans 11 as my IDE.

This tutorial only introduces how Java persistence API works from an open source perspective and does not cover instructions for its use as a tool. It's all about writing application patterns, but it's also good for understanding specific software implementations. You can get the code from my GitHub repository.

Java: not just beans

Java is an object-oriented programming language, which has changed a lot since the release of the first version of Java development tools (JDK) in 1996. To understand its various developments and its virtual machines is a history lesson in itself. In short, much like the Linux kernel, the language has branched in many directions since its release. There are standard versions that are free to the community, enterprise versions for enterprises, and open source alternatives provided by multiple vendors. Major versions are released every six months, and their functions tend to vary greatly, so some research needs to be done before confirming the selection of the version.

All in all, Java has a long history. This tutorial focuses on JDK 11, an open source implementation of Java 11. Because it is still one of the long-term supported versions.

Spring Boot is a module of a large Spring framework developed by Pivotal. Spring is a very popular framework in Java development. It supports a variety of frameworks and configurations, and also provides protection for WEB applications and security. Spring Boot provides the basic configuration for quickly building various types of Java projects. This tutorial uses Spring Boot to quickly write console applications and test cases against databases.

Maven is a project / package management tool developed by Apache. Maven manages packages and their dependencies through POM.xml files. If you have ever used NPM, you may be very familiar with the functions of the package manager. In addition, Maven is also used to build projects and generate functional reports.

Lombok is a library that automatically creates getters/setters methods by adding annotations to object files. Languages like C# have already implemented this feature, and Lombok has only introduced this feature into the Java language.

NetBeans is a popular open source IDE dedicated to Java development. Many of its tools are updated with versions of Java SE and EE.

We will use this set of tools to create a simple application for a fictional bike store. Inserts into collections of Customer and Bike objects are implemented.

Brewing perfect

Navigate to the Spring Initializr page. The site can generate basic projects based on Spring Boot and its dependencies. Select the following options:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Project: Maven Project

Language: Java

Spring Boot: 2.1.8 (or the most stable version)

Project metadata: no matter what name you use, the naming convention is something like com.stephb.

You can keep the Artifact name as "Demo".

Dependencies: adding:

Spring Data MongoDB

Lombok

Click download and open the new project with your IDE (such as NetBeans).

Model layer summary

In the project, the model model represents the specific object of the information extracted from the database. We focus on two objects: Customer and Bike. First, create the dto directory in the src directory; then, create two Java class object files named Customer.java and Bike.java. Its structure is as follows:

Package com.stephb.JavaMongo.dto; import lombok.Getter;import lombok.Setter;import org.springframework.data.annotation.Id; / * * @ author stephon * / @ Getter @ Setterpublic class Customer {private @ Id String id; private String emailAddress; private String firstName; private String lastName; private String address;} Customer.Java

Package com.stephb.JavaMongo.dto; import lombok.Getter;import lombok.Setter;import org.springframework.data.annotation.Id; / * * @ author stephon * / @ Getter @ Setterpublic class Bike {private @ Id String id; private String modelNumber; private String color; private String description Override public String toString () {return "This bike model is" + this.modelNumber + "is the color" + this.color + "and is" + description;}} Bike.java

As you can see, Lombok annotations are used in the object to generate getters/setters methods for the defined attribute properties/ attribute attributes. If you don't want to generate getters/setters methods for all the features of the class, you can define these annotations specifically on the properties. These two classes become containers with data that can be used wherever you want to display information.

Configuration database

I used the Mongo Docker container for this test. If you already have MongoDB installed on your system, you don't have to run the Docker instance. You can also log on to its website, select system information, and follow the installation instructions to install MongoDB.

After installation, you can use the command line, GUI (such as MongoDB Compass), or the IDE driver used to connect to the data source to interact with the new MongoDB server. At this point, you can begin to define data layers for pulling, transforming, and persisting data. To set database access properties, navigate to the applications.properties file in the program and add the following:

Spring.data.mongodb.host=localhostspring.data.mongodb.port=27017spring.data.mongodb.database=BikeStore defines data access object / data access layer

The data access object data access objects (DAO) in the data access layer data access layer (DAL) defines the process of interaction with the data in the database. The amazing thing is that after using spring-boot-starter, most of the work of querying the database has been done.

Let's start with Customer DAO. Create an interface file in the new directory dao under src, and then create a Java class file named CustomerRepository.java, as shown below:

Package com.stephb.JavaMongo.dao; import com.stephb.JavaMongo.dto.Customer;import java.util.List;import org.springframework.data.mongodb.repository.MongoRepository; / * * @ author stephon * / public interface CustomerRepository extends MongoRepository {@ Override public List findAll (); public List findByFirstName (String firstName); public List findByLastName (String lastName);}

This class is an interface that extends or inherits from the MongoRepository class, while the MongoRepository class relies on DTO (Customer.java) and a string, which are used to implement custom function queries. Because you have inherited from this class, you can access a number of method functions that allow you to persist and query objects without having to implement or reference self-defined method functions. For example, after instantiating the CustomerRepository object, you can use the Save function directly. If you need to extend more functions, you can also rewrite these functions. I created some custom queries to search my collection, and these collection objects are my custom elements.

The Bike object also has a storage source responsible for interacting with the database. Very similar to the implementation of CustomerRepository. The implementation is as follows:

Package com.stephb.JavaMongo.dao; import com.stephb.JavaMongo.dto.Bike;import java.util.List;import org.springframework.data.mongodb.repository.MongoRepository; / * * @ author stephon * / public interface BikeRepository extends MongoRepository {public Bike findByModelNumber (String modelNumber); @ Override public List findAll (); public List findByColor (String color);} run the program

Now that you have a way to structure data, you can extract, transform, and persist the data, and then run the program.

Find the Application.java file (it may not be the same name, depending on your application name, but it will all contain "application"). In the place where the class is defined, add implements CommandLineRunner after it. This will allow you to implement the run method to create a command line application. Override the run method provided by the CommandLineRunner interface and include the following to test the BikeRepository:

Package com.stephb.JavaMongo; import com.stephb.JavaMongo.dao.BikeRepository;import com.stephb.JavaMongo.dao.CustomerRepository;import com.stephb.JavaMongo.dto.Bike;import java.util.Scanner;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @ SpringBootApplicationpublic class JavaMongoApplication implements CommandLineRunner {@ Autowired private BikeRepository bikeRepo; private CustomerRepository custRepo Public static void main (String [] args) {SpringApplication.run (JavaMongoApplication.class, args);} @ Override public void run (String...) Args) throws Exception {Scanner scan = new Scanner (System.in); String response = ""; boolean running = true; while (running) {System.out.println ("What would you like to create?\ n C: The Customer\ n B: Bike?\ n X:Close"); response = scan.nextLine () If ("B" .equals (response.toUpperCase () {String [] bikeInformation = new String [3]; System.out.println ("Enter the information for the Bike"); System.out.println ("Model Number") BikeInformation [0] = scan.nextLine (); System.out.println ("Color"); bikeInformation [1] = scan.nextLine (); System.out.println ("Description") BikeInformation [2] = scan.nextLine (); Bike bike = new Bike (); bike.setModelNumber (bikeInformation [0]); bike.setColor (bikeInformation [1]); bike.setDescription (bikeInformation [2]) Bike = bikeRepo.save (bike); System.out.println (bike.toString ());} else if ("X" .equals (response.toUpperCase () {System.out.println ("Bye") Running = false;} else {System.out.println ("Sorry nothing else works right now!");}

The @ Autowired annotation automatically relies on injecting BikeRepository and CustomerRepository Bean. We will use these classes to persist and collect data from the database.

It's ready. You have created a command line application. The application connects to the database and is able to perform CRUD operations with minimal code

Thank you for reading this article carefully. I hope the article "how to use Java to persist API" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report