Quarkus操作数据库,直接使用数据库连接池以及集成jpa

 1.引入依赖:

        
            io.quarkus
            quarkus-agroal
        
        
            io.quarkus
            quarkus-jdbc-mysql
        
        
            io.quarkus
            quarkus-spring-data-jpa
        

2.实体对象:

@Entity(name = "x_user")
public class XUser {

    @Id
    private Long id;
    @Column
    @NotNull(message = "名称不能为空")
    private String name;

    @Column
    @NotNull(message = "年龄不能为空")
    private Integer age;

    @JsonbDateFormat(value = "yyyy-MM-dd HH:mm:ss")
    @Column
    @NotNull(message = "生日不能为空")
    private LocalDateTime birthday;

3.配置数据库连接:

quarkus.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
quarkus.datasource.driver=com.mysql.cj.jdbc.Driver
quarkus.datasource.username=root
quarkus.datasource.password=123456
quarkus.datasource.min-size=8
quarkus.datasource.max-size=8

4.直接使用数据库连接池进行操作数据库:

    @Inject
    AgroalDataSource dataSource;

    @Path("save")
    @POST
    @Cut
    public Object save(@Valid XUser xUser) {
        try {
            Connection connection = dataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("insert into x_user values(?,?,?,?)");
            preparedStatement.setLong(1, LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
            preparedStatement.setString(2, xUser.getName());
            preparedStatement.setInt(3, xUser.getAge());
            preparedStatement.setObject(4, xUser.getBirthday());
            int count = preparedStatement.executeUpdate();
            if (count < 1) {
                return "fail";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "ok";
    }

5.使用jpa操作数据库连接池:

public interface UserMapper extends CrudRepository {
}
    @Inject
    UserMapper userMapper;

    @Path("list")
    @GET
    @Cut
    public Object list() {
        return userMapper.findAll();
    }

 

你可能感兴趣的:(Quarkus操作数据库,直接使用数据库连接池以及集成jpa)