Home > Java > javaTutorial > body text

How to perform persistence and data storage in Java development

PHPz
Release: 2023-10-08 16:14:04
Original
865 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template