//在service包中写下面代码就可以写SQL语句
@Autowired
QueryDAO queryDao;
@Autowired
UpdateDAO updateDao;
//查询语句的函数
public UserBean searchUser(UserBean frm) {
frm = queryDao.executeForObject("user.selectuser", frm, UserBean.class);
//frm.setUserId("test");
return frm;
}
//插入语句的函数
public int insert(UserBean frm){
int result=0;
try {
result = updateDao.execute("user.insertuser", frm);
} catch(Exception e) {
return result;
}
return result;
}
//在Controller包中写如下代码
//查询代码
public String initLogin(UserBean userBean, Model model) {
UserBean result = helloWorldService.searchUser(userBean);
model.addAttribute("userBean", result);
return "login";
}
//插入代码
public String initinsert(UserBean userinsert, Model model) {
int insert=helloWorldService.insert(userinsert); //***注意是int类型
UserBean user=new UserBean();
model.addAttribute("userBean", user);
if(insert==1){
model.addAttribute("message", "OK!");
}else{
model.addAttribute("message", "failed!");
}
return "insert";
}
//SQL语句代码如下
<sqlMap namespace="user"> //注意user
<select id="selectuser" //注意selesctuser
parameterClass="cn.training.bean.UserBean"
resultClass="cn.training.bean.UserBean">
SELECT
userid as userId,
username as username
FROM
user
WHERE
userid = #userId#
</select>
<insert id="insertuser" //注意insertuser
parameterClass="cn.training.bean.UserBean">
insert into user(userid) values(#userId#)
</insert>
<update id="updateuser"
parameterClass="cn.training.bean.UserBean">
update user set username=#username#
WHERE
userid=#userId#
</update>
</sqlMap>
//以上注意的内容在service包中赋值有使用到
//数据库传值过程
1.页面中的值先传给controller中的userbean,
2.
UserBean result = helloWorldService.searchUser(userBean);
model.addAttribute("userBean", result);
在controller中的语句把值传给service包中
3.frm = queryDao.executeForObject("user.selectuser", frm, UserBean.class);
service中的语句把值传到SQL语句中用##号将齐给与赋值//userid = #userId#
执行SQL语句对数据库进行操作
用resultClass="cn.training.bean.UserBean"接受返回结果。