SpringBoot資料訪問之整合mybatis註解版
阿新 • • 發佈:2021-08-29
建立資料庫:
use vuesite; CREATE TABLE city ( id INT PRIMARY KEY auto_increment, name VARCHAR(255), state VARCHAR(255), country VARCHAR(255) );
建立實體類:
package com.xbhog.pojo; import lombok.Data; @Data public class City { private Long id; private String name;private String state; private String country; }
建立Mapper:
建立CityMapper並採用註解的方式實現sql對映的問題:
package com.xbhog.Mapper; import com.xbhog.pojo.City; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface CityMapper { @Select("select * from user where id = #{id}")public City getCityId(Long id); }
建立Service:
package com.xbhog.service; import com.xbhog.Mapper.CityMapper; import com.xbhog.pojo.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CityService { @Autowired CityMapper cityMapper;public City getCityId(Long id){ return cityMapper.getCityId(id); } }
使用Service註解宣告,並將該類加入到容器中,方便後面呼叫,在service層呼叫Mapper層的方法。
建立Controller:
import com.xbhog.pojo.City; import com.xbhog.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; @Controller public class Mycontro { @Autowired CityService cityService; @ResponseBody @GetMapping("/city") public City getCity(@RequestParam("id") Long id){ return cityService.getCityId(id); } }
增加資料庫資訊:
測試:
mybatis混合版:
我們在CItyMapper中新增一個方法:
package com.xbhog.Mapper; import com.xbhog.pojo.City; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface CityMapper { @Select("select * from city where id = #{id}") public City getCityId(Long id); public void addCity(City city); }
這個方法我們採用配置檔案來繫結。
建立CityMapper.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.xbhog.Mapper.CityMapper"> <insert id="addCity" parameterType="com.xbhog.pojo.City"> insert into city(`name`,`state`,`country`) values (#{name},#{state},#{country}); </insert> </mapper>
其中名稱空間與CityMapper要對應,進行插入操作。
在Service層增加方法:
package com.xbhog.service; import com.xbhog.Mapper.CityMapper; import com.xbhog.pojo.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CityService { @Autowired CityMapper cityMapper; public void addCity(City city){ cityMapper.addCity(city); } }
https://www.cnblogs.com/xbhog/p/15201414.html
故鄉明