创建项目可以查看我上一个博客
项目目录
2.4整合jdbc,在application.properties或者使用application.yml中加入jdbc的支持
#数据库配置参数
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///invoicingsystem
#设置实体类别名
mybatis.type-aliases-package=com.example.demo.entity
#映射Mapper配置文件的地址
mybatis.mapper-locations=com/example/demo/dao/*.xml
创建实体,导入getset方法
public class Users implements Serializable {
private int uid;
private String userName;
private String password;
private String realName;
}
创建接口
@Repository("iUsersDao")
public interface IUsersDao {
Users login(@Param("username") String username);
}
创建IUsersdao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.IUsersDao">
<!-- 目的:为dao接口方法提供sql语句配置 -->
<select id="login" resultType="com.example.demo.entity.Users">
<!-- 具体的sql -->
select * from users where userName=#{username}
</select>
</mapper>
创建service接口
public interface IUsersService {
Users login(String userName, String password);
}
创建service的实现类
@Service("iUsersService")
public class UsersSerivceImpl implements IUsersService{
//获取dao接口对象
@Resource(name = "iUsersDao")
private IUsersDao iUsersDao;
@Override
public Users login(String username, String password) {
Users login = iUsersDao.login(username);
//判读如果返回有值则登陆成功,返回对象
//如果登陆失败,返回null
if (login != null && login.getPassword().equals(password)) {
return login;
}
return null;
}
}
创建IUsersController
@Controller
public class IUsersController {
@Resource(name = "iUsersService")
private IUsersService iUsersService;
@RequestMapping("/tologin")
public String toString(){
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
Users user = iUsersService.login(username, password);
if(user!=null){
request.getSession().setAttribute("user", user);
return "index";
}else{
return "login";
}
}
在DemoApplication 里面添加@MapperScan({“com.example.demo.*”})
@SpringBootApplication
@MapperScan({"com.example.demo.*"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}