Home  >  Article  >  Java  >  How to use ORM framework in Java backend function development?

How to use ORM framework in Java backend function development?

WBOY
WBOYOriginal
2023-08-05 10:01:051219browse

How to use ORM framework in Java back-end function development?

The ORM (Object Relational Mapping) framework is a tool widely used in Java back-end development. It can map the table structure in the database into objects and provide a convenient API to operate the database. This article will introduce how to use ORM framework in Java backend development, with code examples.

  1. Choose a suitable ORM framework

Before using the ORM framework, we need to choose a suitable framework first. In Java development, Hibernate and MyBatis are two popular ORM frameworks. Among them, Hibernate is a fully automated framework that can automatically generate and execute SQL statements, while MyBatis requires manual writing and maintenance of SQL statements. Choose a framework that suits you based on your personal needs and development habits.

  1. Configuring the ORM framework

Whether using Hibernate or MyBatis, we need to configure the framework first. The following takes Hibernate as an example to introduce how to configure it.

First, we need to add Hibernate-related dependencies to the project's dependencies. In the Maven project, you can add the following code in the pom.xml file:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.32.Final</version>
</dependency>

Then, we need to create a Hibernate configuration file (usually named hibernate.cfg.xml) in the project, which is used to Configure database connection and other information. The following is a simple example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
    </session-factory>
</hibernate-configuration>

In the configuration file, you need to fill in the corresponding database connection information, such as database driver, database URL, user name and password, etc.

  1. Define entity classes

The ORM framework can map the table structure in the database into Java objects, so we need to define entity classes in the project. The following is a simple example:

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    // 省略构造方法、Getter和Setter
}

In the entity class, we use annotations to mark the database columns corresponding to each field.

  1. Writing the data access layer (DAO)

The data access layer (DAO) is responsible for interacting with the database. We can use the API provided by the ORM framework to simplify the operation.

The following is a simple example:

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public User findById(Long id) {
        Session session = sessionFactory.getCurrentSession();
        return session.get(User.class, id);
    }

    @Override
    public void save(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

    @Override
    public void update(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.update(user);
    }

    @Override
    public void delete(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(user);
    }
}

In the data access layer, we use the @Repository annotation to declare the class as a Spring Bean, and use the @Autowired annotation to inject the SessionFactory.

  1. Use the service layer to call the data access layer

Finally, we can use the interface of the data access layer in the service layer to call database operations.

The following is a simple example:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public User getUserById(Long id) {
        return userDao.findById(id);
    }

    @Override
    public void saveUser(User user) {
        userDao.save(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.update(user);
    }

    @Override
    public void deleteUser(User user) {
        userDao.delete(user);
    }
}

In the service layer, we use the annotation @Service to declare the class as a Spring Bean, and use the @Autowired annotation to inject UserDao.

The above are the basic steps for using the ORM framework in Java back-end function development. By using the ORM framework, we can operate the database more conveniently and improve development efficiency.

I hope this article can help you understand and apply the ORM framework.

The above is the detailed content of How to use ORM framework in Java backend function development?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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