springboot框架中如何在xml中select数据库信息把数据返回到Servicelmpl.java中使用

1. springboot框架中如何在xml中select数据库信息把数据返回到Servicelmpl.java中使用

在Spring Boot框架中,可以使用MyBatis或者JdbcTemplate来操作数据库,以下给出两种方式的实现方法:

  1. 使用MyBatis
    步骤如下:

(1)在pom.xml中添加以下依赖:

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.2.0</version>
</dependency>

(2)在application.properties中配置数据库信息:

spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

(3)编写Mapper接口:

public interface UserMapper {
    User getUserById(int id);
}

(4)编写Mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
  <select id="getUserById" parameterType="int" resultMap="resultMap">
    select * from user where id=#{id}
  </select>
  <resultMap id="resultMap" type="com.example.entity.User">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="age" column="age"/>
  </resultMap>
</mapper>

(5)在ServiceImpl.java中注入Mapper,并使用:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }
}
  1. 使用JdbcTemplate
    步骤如下:

(1)在pom.xml中添加以下依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>

(2)在application.properties中配置数据库信息:

spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password

(3)在ServiceImpl.java中注入JdbcTemplate,并使用:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserById(int id) {
        String sql = "SELECT * FROM user WHERE id = ?";
        User user = jdbcTemplate.queryForObject(
                sql, new Object[]{id},
                (rs, rowNum) -> new User(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getInt("age")
                )
        );
        return user;
    }
}

赛文市场营销

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注