Home Java javaTutorial How to perform persistence and data storage in Java development

How to perform persistence and data storage in Java development

Oct 08, 2023 pm 04:14 PM
Persistence data storage java development

How to perform persistence and data storage in Java development

How to perform persistence and data storage in Java development requires specific code examples

In Java development, persistence and data storage are a very important part. It involves saving data to disk or other persistent media so that it can continue to be used when the program is re-run. This article will introduce common persistence and data storage technologies in Java and provide code examples.

1. File IO
File IO is one of the most basic and commonly used data storage methods. By using Java's input and output streams and file processing classes, you can write data to files and read data from files when needed.

Example 1: Using file IO for data storage

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class FileIODemo {

    public static void main(String[] args) {
        String data = "Hello, World!";
        String fileName = "data.txt";

        // 写入数据到文件
        try {
            FileWriter writer = new FileWriter(fileName);
            writer.write(data);
            writer.close();
            System.out.println("数据写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 从文件中读取数据
        try {
            FileReader reader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println("读取到数据:" + line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
Copy after login

Example 2: Using file IO to save and read objects

import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

public class ObjectIODemo {

    public static void main(String[] args) {

        // 定义需要保存的对象
        Person person = new Person("Alice", 20);

        // 将对象保存到文件
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("person.ser");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(person);
            objectOutputStream.close();
            System.out.println("对象保存成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 从文件中读取对象
        try {
            FileInputStream fileInputStream = new FileInputStream("person.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Person restoredPerson = (Person) objectInputStream.readObject();
            objectInputStream.close();
            System.out.println("读取到对象:" + restoredPerson);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

}
Copy after login

2. Relational database
Relational database is An efficient, scalable and durable way to store data. Java provides a variety of APIs for operating databases, such as JDBC (Java Database Connectivity) and JPA (Java Persistence API).

Example 3: Using JDBC for data storage

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCDemo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/mydb";
        String username = "root";
        String password = "123456";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            Statement statement = connection.createStatement();

            // 创建表
            String createTableSQL = "CREATE TABLE IF NOT EXISTS employees (id INT PRIMARY KEY, name VARCHAR(50))";
            statement.executeUpdate(createTableSQL);

            // 插入数据
            String insertDataSQL = "INSERT INTO employees VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')";
            statement.executeUpdate(insertDataSQL);

            // 查询数据
            String selectDataSQL = "SELECT * FROM employees";
            ResultSet resultSet = statement.executeQuery(selectDataSQL);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("id: " + id + ", name: " + name);
            }

            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
Copy after login

Example 4: Using JPA for data storage

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JPADemo {

    public static void main(String[] args) {

        // 创建实体管理工厂
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager entityManager = factory.createEntityManager();

        // 创建事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        try {
            // 创建实体对象
            Person person1 = new Person("Alice", 20);
            Person person2 = new Person("Bob", 25);

            // 保存实体对象
            entityManager.persist(person1);
            entityManager.persist(person2);

            // 提交事务
            transaction.commit();
            System.out.println("对象保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            entityManager.close();
            factory.close();
        }
    }

}

@Entity
class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;
    private int age;

    // 省略构造函数、getter和setter等

}
Copy after login

The above are the persistence and data storage technologies commonly used in Java development and Its code sample. According to actual needs, choosing the appropriate technology and method for data storage can effectively improve the reliability and efficiency of the program. Hope the content of this article is helpful to you!

The above is the detailed content of How to perform persistence and data storage in Java development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles