如何从Spring

时间:2017-11-09 22:47:02

标签: json spring spring-mvc spring-boot stored-procedures

如何在spring中通过存储过程将数据插入表中?

任何人都可以参考一个例子。我的存储过程有一些自动生成的值。

CREATE PROCEDURE [dbo].[usp_employee_insert]
    @full_name varchar(75),@gender varchar(6), @department varchar(25), _
    @position varchar(50),@salary float
AS
BEGIN
    INSERT INTO employees (full_name,gender,department,position,salary)
    VALUES  (@full_name,@gender,@department,@position,@salary)
END

2 个答案:

答案 0 :(得分:0)

这将是这样的:

public class UspEmployeeInsert extends StoredProcedure {

    private final String NAME = "usp_employee_insert";

    public UspEmployeeInsert(DataSource dataSource) {

        setDataSource(dataSource);
        setSql(NAME);

        declareParameter(new SqlParameter("full_name", Types.VARCHAR));
        declareParameter(new SqlParameter("gender", Types.VARCHAR));
        declareParameter(new SqlParameter("department", Types.DATE));
        declareParameter(new SqlParameter("position", Types.VARCHAR));
        declareParameter(new SqlParameter("salary", Types.FLOAT));

        compile();
    }

    public void execute(
        String fullName,
        String gender,
        Date deparment,
        String position,
        Float salary){

        final Map<String, Object> parameters = new HashMap<>(5);
        parameters.put("full_name", fullName);
        parameters.put("gender", gender);
        parameters.put("department", deparment);
        parameters.put("position", position);
        parameters.put("salary", salary);

        execute(parameters);
    }
}

或者你可以这样做:

@Repository
public class UspEmployeeRepository {

    private final String NAME = "usp_employee_insert";
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public UspEmployeeRepository(DataSource dataSource) {

        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void insert(
        String fullName,
        String gender,
        Date deparment,
        String position,
        Float salary){

        jdbcTemplate.update(
            "{ call usp_employee_insert(?,?,?,?,?) }",
            fullName,gender,deparment,position,salary
        );
    }
}

答案 1 :(得分:0)

首先,您应该添加EntityManager来访问数据库:

@PersistenceContext
private EntityManager entityManager;

此外,您应该向您的班级添加StoredProcedureQuery界面,这样您就可以使用多种方法与存储过程进行互动,例如registerStoredProcedureParameter,{{1} },setParameter等。

假设您的execute实体具有存储过程中提到的属性,您可以将此代码段作为示例:

Person