我已经在 MySQL存储过程 e中编写了一些逻辑。我正在将 spring boot与hibernate一起使用 。我有一个使用 IN OUT 参数的登录过程。从我的登录过程中,我想将消息传递给用户。但是我不知道如何在Spring Boot中调用存储过程。我的代码在下面。
CREATE PROCEDURE login(IN in_user_id varchar(100), IN in_password varchar(100), OUT out_code INT, OUT out_message varchar(100)) BEGIN IF in_user_id IS NULL OR in_user_id = '' THEN SET out_code = 1; SET out_message = 'Please Enter Your First Name.'; END IF; /*Logi Here*/ END;
@Entity @Table(name = "user") @NamedStoredProcedureQueries({ @NamedStoredProcedureQuery( name = "do_login", procedureName = "login", resultClasses = { LoginModel.class }, parameters = { @StoredProcedureParameter( name = " in_user_id", type = String.class, mode = ParameterMode.IN), @StoredProcedureParameter( name = "in_password", type = String.class, mode = ParameterMode.IN), @StoredProcedureParameter( name = "out_code", type = Integer.class, mode = ParameterMode.OUT), @StoredProcedureParameter( name = "out_message", type = String.class, mode = ParameterMode.OUT) }), }) public class LoginModel implements Serializable { @NotEmpty private String userid; @NotEmpty private String password; //Here is getter setter }
@RequestMapping(value = "/login", method = RequestMethod.POST) public String doLogin(@ModelAttribute("webLoginForm") @Valid LoginModel registrationModel, BindingResult bindingResult, Model model, Errors error) { if(error.hasErrors()) { return "login"; } // Here I want to check My Procedure result & redirect to welcome page //return "redirect:/welcome"; return "login"; }
我已经使用了存储库,但是这里没有写任何东西。我已经用过波纹管了..
public interface LoginRepository extends CrudRepository<LoginModel, Integer>{
}
您可以使用javax.persistence.StoredProcedureQuery调用存储过程。您甚至不需要在实体上声明任何内容。 我建议将过程调用逻辑移至服务,然后从控制器中调用服务方法。
例如:
@Service public class LoginServiceImpl implements LoginService { @PersistenceContext private EntityManager entityManager; public Boolean checkUsernameAndPassword(String username, String password) { //"login" this is the name of your procedure StoredProcedureQuery query = entityManager.createStoredProcedureQuery("login"); //Declare the parameters in the same order query.registerStoredProcedureParameter(1, String.class, ParameterMode.IN); query.registerStoredProcedureParameter(2, String.class, ParameterMode.IN); query.registerStoredProcedureParameter(3, Integer.class, ParameterMode.OUT); query.registerStoredProcedureParameter(4, String.class, ParameterMode.OUT); //Pass the parameter values query.setParameter(1, username); query.setParameter(2, password); //Execute query query.execute(); //Get output parameters Integer outCode = (Integer) query.getOutputParameterValue(3); String outMessage = (String) query.getOutputParameterValue(4); return true; //enter your condition } }
然后,您可以在注入之后从Controller调用此方法LoginService。
LoginService