前言
之前使用过mybatis和mybatis plus来调用数据库函数和存储过程,这也是目前使用比较广泛和流行的方法,但是今天遇到一个要求就是在一个项目中添加函数调用的功能,这个项目不是使用的mybatis,而是JPA,所以想找一下如何使用JPA调用函数的方法,但是好像没有特别好的方法(可能是我没找到)。
后来找到一篇英文解答,使用的是JDBC,然后我试了一下是可以实现功能的,写篇文章记录一下。
一、举例说明
比如我们有这个表,现在测试用函数从这个表中查出我们想要的数据
±-------±-----------±---------------+
| Name | DOB | Location |
±-------±-----------±---------------+
| Amit | 1989-09-26 | Hyderabad |
| Sumith | 1989-09-01 | Vishakhapatnam |
| Sudha | 1980-09-01 | Vijayawada |
±-------±-----------±---------------+
函数如下:
CREATE FUNCTION getDob(emp_name VARCHAR(50)) RETURNS DATE
BEGIN
declare dateOfBirth DATE;
select DOB into dateOfBirth from EMP where Name = emp_name;
return dateOfBirth;
END
二、主要代码如下
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class CallingFunctionsExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
//tableName替换为自己的数据库的名字
String mysqlUrl = "jdbc:mysql://localhost/tableName";
//root替换为自己的数据库的账号名字,12345678为密码
Connection con = DriverManager.getConnection(mysqlUrl, "root", "12345678");
System.out.println("Connection established......");
//Preparing a CallableStatement to call a function
//function为所要调用的函数的名字
//(?)表示输入参数
CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
//Registering the out parameter of the function (return type)
/Types.DATE表示输出参数的类型
cstmt.registerOutParameter(1, Types.DATE);
//Setting the input parameters of the function
//Amit表示输入参数
cstmt.setString(2, "Amit");
//Executing the statement
cstmt.execute();
//打印出输出的值
System.out.print("Date of birth: "+cstmt.getDate(1));
}
}
最后输出:
Connection established…
Date of birth: 1989-09-26