openTSP连接sqlServer数据库&jpa调用存储过程

  openTSP框架下的模块都是连接mysql数据库,近期青汽有连接sqlServer数据库的需求,在调研后配置了sqlServer数据库,使用jpa调用存储过程,中间也踩了不少坑,总结一下,避免大家再掉进去。

  1、首先配置sqlServer的依赖

  

        <dependency>
            <groupId>com.microsoft.sqlservergroupId>
            <artifactId>sqljdbc4artifactId>
            <version>4.0version>
        dependency>

  注意:从maven私服下载jar包失败,为了简便使用,可以先下载sqljdbc4.jar,然后用命令行切换到jar包所在路径,执行mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0,这样就把jar包安装到了本地依赖仓库。

  2、修改数据库连接配置文件application-xxx.properties

  

spring.datasource.url=jdbc:sqlserver://ip:1433;DatabaseName=test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.validation-query=SELECT 1;
spring.datasource.test-on-borrow=true
spring.datasource.test-while-idle=true
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

spring.datasource.max-active=200
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

spring.jpa.database = SQLSERVER
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2005Dialect
spring.jpa.show-sql=true
spring.jta.bitronix.datasource.allow-local-transactions=true

  sqlServer的driverClass是com.microsoft.sqlserver.jdbc.SQLServerDriver

  

3、java连接sqlServer数据库

  1)创建sql文件test-dynamic.xml

  

    <sql-query name="queryTest">
        
           SELECT
                jf0 ,
                jf1 ,
                jf2 ,
                jf3 ,
                jf4
            FROM
                testTable
        ]]>
    sql-query>
    

  2)dao层调用

  

 public String getJF01(TestCommand command)
    {

        List list = dao.sqlFind("queryTest",command, TestPojo.class);
        for(TestPojo pojo : list) {
            System.out.println("pojo=" + pojo);
        }
        return list.get(0).toString();
    }

  TestPojo里就是设置了jf0到jf5这几个属性以及set、get方法,不再赘述。

 

4、JPA调用sqlServer存储过程

  1)Entity

  采用注解的方式,要和数据库的1张表关联,随便一张表都可以。多个存储过程用NamedStoredProcedureQueries。

@Entity
@Table(name="testTable")
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "testProc1", procedureName = "testProc1", parameters = { //name是JPA中的存储过程的名字, procedureName是数据库存储过程的名字
                @StoredProcedureParameter(mode = ParameterMode.IN, name = "inParam1", type = String.class),
                @StoredProcedureParameter(mode = ParameterMode.IN, name = "inParam2", type = String.class)}),
        @NamedStoredProcedureQuery(name = "testProc", procedureName = "testProc", parameters = {
                @StoredProcedureParameter(mode = ParameterMode.IN, name = "inParam1", type = String.class),
                @StoredProcedureParameter(mode = ParameterMode.IN, name = "inParam2", type = String.class),
                @StoredProcedureParameter(mode = ParameterMode.OUT, name = "outParam", type = String.class) })
})
public class TestEntity implements java.io.Serializable
{
    @Id
    private String name;
}

  2)Repository 

  参数使用@Param,注解内容要和entity的参数名一致。

@Repository
public interface TestRepository extends JpaRepository, JpaSpecificationExecutor
{
    @Procedure(name="testProc")//和entity的jpa的存储过程名一致
    String testProc(@Param("inParam1") String inParam1,@Param("inParam2") String inParam2 );
}

  3)Service

  直接调用repository,就有单个返回值。

@Service
public class TestService extends BaseService {
    
    @Autowired
    private TestRepository repository;

    public String testProc(TestCommand command)
    {
        String out = repository.testProc1("chen",String.valueOf(System.currentTimeMillis()));
        System.out.println("outParam = "+ out);
        return out;
    }
}

 

5、多个out出参问题

注意:jpa只支持1个OUT出参的存储过程,暂时无法调用多个OUT出参的存储过程(可以接收select语句的多个出参)。我们项目里恰巧是多个OUT出参存储过程,而且还修改不了存储过程,只能1个单出参存储过程,封装多出参存储过程,并把多个出参合并成1个。

  inner多出参存储过程:

ALTER PROCEDURE [dbo].[inProc]
  @inParam1 VARCHAR(20),
  @inParam2 VARCHAR(20),
  @outParam1 VARCHAR(20) OUTPUT,
  @outParam2 VARCHAR(20) OUTPUT
AS
BEGIN
  insert into mytable values(@inParam1,@inParam2);
  set @outParam1 = 'result123';
  set @outParam2 = 'result456';
END
View Code

  外层封装的单出参存储过程

ALTER PROCEDURE [dbo].outProc
  @inParam1 varchar(20) ,
  @inParam2  varchar(20) ,
  @outParam1  varchar(20) output
AS
declare @out1 varchar(20)
declare @out2 varchar(20)
BEGIN
    exec inProc @inParam1,@inParam2,@out1 output,@out2 output;

    set @outParam1 = @out1 + @out2 ;
END
View Code

面对多个out出参,也可以采用我们最熟悉度jdbc方式,关键点就是获取数据库连接connection。

Session session = (org.hibernate.Session) entityManager.getDelegate();
SessionFactoryImplementor sf = (SessionFactoryImplementor) session.getSessionFactory();
try {
    Connection connection  = sf.getConnectionProvider().getConnection();//获取数据库connection连接
    CallableStatement cs =  connection.prepareCall("{call inProc(?,?,?,?)}");
    cs.setString(1,"chen");
    cs.setString(2,String.valueOf(System.currentTimeMillis()));
    cs.registerOutParameter(3, Types.VARCHAR);//注册第一个out出参
    cs.registerOutParameter(4, Types.VARCHAR);//注册第二个out出参
    cs.execute();
    String code = cs.getString(3);//获取第一个out出参
    String message = cs.getString(4);//获取第二个out出参
    System.out.println("code="+code+",message="+message);
} 
catch (SQLException e) 
{
    e.printStackTrace();
}
finally
{
    cs.close();
    connection.close();
}

 

转载于:https://www.cnblogs.com/chenjack/p/6404376.html

你可能感兴趣的:(openTSP连接sqlServer数据库&jpa调用存储过程)