Mybatis前期
Mybatis是目前最流行的数据持久层框架
- Mybatis框架可以根据用户通过注解或配置文件所指的的SQL语句自动生成对应的JDBC代码,从而提高了开发效率
如何使用Mybatis框架
-
先创建一个Springboot工程,在选择界面选择Web的Spring Web和SQL中的Mybatis Framework、MySQL Driver。之后点击完成,注意环境的配置,springboot和maven可能虎有冲突,需要自己将相关文件配置好,可以参考百度方法。
或者可以直接新建maven工程,之后再引入相关的依赖。
-
创建完工程后 需要在application.properties配置文件中添加下面连接数据库的信息 否则工程无法正常启动 会报如下错误
spring.datasource.url=jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false spring.datasource.username=root spring.datasource.password=root
-
创建好工程之后就可以添加页面代码实现功能
<!--首页--> <body> <h1>商品管理系统Mybatis版</h1> <a href="/insert.html">添加商品</a> <a href="/select">商品列表</a> <a href="/update.html">修改商品</a> </body> <!--添加页--> <body> <h1>添加商品</h1> <form action="/insert"> <input type="text" name="title"> <input type="text" name="num"> <input type="text" name="price"> <input type="submit" value="点击添加"> </form> </body> <!--修改页--> <body> <h1>修改页面</h1> <form action="/update"> <input type="text" name="id" placeholder="id"> <input type="text" name="title" placeholder="标题"> <input type="text" name="num" placeholder="库存"> <input type="text" name="price" placeholder="价格"> <input type="submit" value="点击修改"> </form> </body>
//Mybatis框架需要引入Mapper接口,Mapper相当于我们之前写的JDBC得代码,即不需要我们去手动写数据库的代码,引入接口后虎自动生成,提高了我们的开发效率。 //ProductController类代码 @RestController public class ProductController { //自动装配注解,此注解是Spring提供的,会结合Mybatis框架自动生成一个实现类,并实例化此实现类赋值给的马胖胖儿变量。 @Autowired ProductMapper mapper; @RequestMapping("/insert") public String insert(Product product){//添加 System.out.println("product = " + product); mapper.insert(product);//直接调用Mapper中的insert方法 return "添加成功!<a href='/'>返回首页</a>"; } @RequestMapping("/select") public String selcet(){//查询列表 List<Product> list = mapper.select(); //将集合中的数据封装在表格中进行输出(仅为实验,后续不会这样写) String html = "<table border='1'>"; html+="<tr><th>id</th><th>标题</th><th>库存</th><th>价格</th><th>操作</th></tr>"; //遍历商品集合 for (Product p: list) { html+="<tr>"; html+="<td>"+p.getId()+"</td>"; html+="<td>"+p.getTitle()+"</td>"; html+="<td>"+p.getNum()+"</td>"; html+="<td>"+p.getPrice()+"</td>"; html+="<td><a href='/delete?id="+p.getId()+"'>删除</a></td>"; html+="</tr>"; } html+="</table>"; return html; } @RequestMapping("/delete") public String delete(int id){//删除 mapper.deleteById(id); return "删除完成!<a href='/select'>返回列表</a>"; } @RequestMapping("/update") public String update(Product product){//修改 System.out.println("product = " + product); mapper.updateById(product); return "修改完成!<a href='/select'>返回列表</a>"; } } //ProductMapper代码 @Mapper public interface ProductMapper { @Insert("insert into product values(null,#{title},#{num},#{price})") void insert(Product product);//添加 @Select("select * from product") List<Product> select();//查询 @Delete("delete from product where id=#{id}") int deleteById(int id);//删除 @Update("update product set title=#{title},num=#{num},price=#{price} where id=#{id}") void updateById(Product product);//修改 }