SpringBoot初學(4)– JdbcTemplate和Mybatis


前言

  github: https://github.com/vergilyn/SpringBootDemo

  代碼位置:

image

一、Spring Boot集成JdbcTemplate或NamedParameterJdbcTemplate

  spring boot中JdbcTemplate與NamedParameterJdbcTemplate都是被自動配置的,所以只要注入就可用。(在傳統的spring中NamedParameterJdbcTemplate並沒有被自動配置)

  必須准備:

    如果你使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa 'starter POMs',你將會自動獲取對tomcat-jdbc的依賴。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

application.properties:

#### 28.1.2. 連接到一個生產環境數據庫
## 注:其他的連接池可以手動配置。如果你定義自己的DataSource bean,自動配置不會發生。
####

## Spring Boot能夠從大多數數據庫的url上推斷出driver-class-name,那么你就不需要再指定它了。
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
## 默認會從url推斷driver class
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username=vergilyn
spring.datasource.password=409839163

## JDNI
# spring.datasource.jndi-name=java:jboss/datasources/customers
/* Spring的JdbcTemplate和NamedParameterJdbcTemplate類是被自動配置的,
 * 你可以在自己的beans中通過@Autowire直接注入它們。
 */
@Repository
public class JdbcTemplateDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private NamedParameterJdbcTemplate namedJdbc;

	@SuppressWarnings("unused")
	public Long testDao(){
		Map<String,Object> param = new HashMap<String,Object>();
		String sql = " select count(*) from child";
		if(true){
			sql += "  where child_name = :name ";
			param.put("name", "周一");
		}
		Long count = this.namedJdbc.queryForObject(sql, param, Long.class);
		System.out.println(count);
		return count;
	}
}
@SpringBootApplication
@RestController
public class DatabaseApplication {
	@Autowired
	private JdbcTemplateDao dao;
	public static void main(String[] args) {
		SpringApplication.run(DatabaseApplication.class, args);
	}
	@RequestMapping("/jdbc")
	public String testDao(){
		return dao.testDao()+"";
	}
}

二、Spring boot集成Mybatis

  2.1 准備
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.0</version>
</dependency>
  2.2 xml模式的mybatis配置

    mybatis的sql映射xml, mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.vergilyn.demo.springboot.mybatis.domain"/>
    </typeAliases>
    <mappers>
        <mapper resource="config/mybatis/mapper/CityMapper.xml"/>
        <mapper resource="config/mybatis/mapper/HotelMapper.xml"/>
    </mappers>
</configuration>

    application.properties中對應要指明此映射路徑。

    application.properties:

## spring.datasource.schema=classpath:config/mybatis/init-oracle.sql
mybatis.config-location=classpath:config/mybatis/mybatis-config.xml

    mybatis的mapper定義:

<?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.vergilyn.demo.springboot.mybatis.mapper.HotelMapper">
    <select id="selectByCityId" resultType="Hotel">
        select * from hotel where city = #{id}
    </select>
</mapper>
HotelMapper.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.vergilyn.demo.springboot.mybatis.mapper.CityMapper">
    <select id="selectCityById" resultType="City">
        select * from city where id = #{id}
    </select>
</mapper>

CityMapper.xml

    mybatis的domain定義:

public class City implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long id;

	private String name;

	private String state;

	private String country;

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getState() {
		return this.state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return this.country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public String toString() {
		return getId() + "," + getName() + "," + getState() + "," + getCountry();
	}

}
City.java
public class Hotel implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long city;

	private String name;

	private String address;

	private String zip;

	public Long getCity() {
		return city;
	}

	public void setCity(Long city) {
		this.city = city;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getZip() {
		return zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	@Override
	public String toString() {
		return getCity() + "," + getName() + "," + getAddress() + "," + getZip();
	}

}
Hotel.java

    mybatis的dao定義,mybatis的SqlSession可直接注入:

@Component
public class CityDao {
	@Autowired
	private SqlSession sqlSession;

	public City selectCityById(long id) {
		return this.sqlSession.selectOne("selectCityById", id);
	}

}

    測試代碼:

@SpringBootApplication
public class MybatisApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(MybatisApplication.class);
		app.setAdditionalProfiles("mybatis");
		app.run(args);
	}
	@Autowired
	private CityDao cityDao;


	@Override
	public void run(String... args) throws Exception {
		System.out.println(this.cityDao.selectCityById(1));
	}

}
  2.3 mybatis注解形式

    相對於xml形式,使用注解模式可減少很多xml的定義。例如:無需定義映射sql的mybatis-config.xml,*Mapper.xml中的sql也可以用注解寫java文件中,application.properties中無需配置任何指定。

    但,個人偏向於還是在xml中寫sql。

    注解形式的domain與xml形式的是一樣的,jar的引用也是一樣的。

    注解形式的*Mapper.java定義,主要是注解org.apache.ibatis.annotations.Mapper:

@Mapper
public interface CityMapper {
	// 混用xml形式
	City selectByCityId(int city_id);

	/**
	 * 注解形式不需要通過dao調用*Mapper.xml。所以可以不寫dao、*Mapper.xml、mybatis-config.xml
	 * @param i
	 * @return
	 */
	@Select("select * from city where id = #{id}")
	City selectByAnnotation(int i);
}
@Mapper
public interface HotelMapper {

	Hotel selectByHotelId(int city_id);

}
  以上可能並不是混用xml,反正要用xml,那么相應的application.properties中就需要指明mybatis-config.xml。 

  (一篇不錯的介紹mybatis中Mapper的文章: Mybatis中配置Mapper的方法 )

  測試代碼:

@SpringBootApplication
public class MybatisApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(MybatisApplication.class);
		app.setAdditionalProfiles("mybatis");
		app.run(args);
	}
	@Autowired
	private CityDao cityDao;
	@Autowired
	private HotelMapper hotelMapper;
	@Autowired
	private CityMapper cityMapper;


	@Override
	public void run(String... args) throws Exception {
		System.out.println(this.cityDao.selectCityById(1));
		System.out.println(this.cityMapper.selectByAnnotation(1));
		System.out.println(this.hotelMapper.selectByHotelId(1));
	}

}

三、題外話

  到現在,主要用過的有hibernate、mybatis、JdbcTemplate。個人最喜歡的還是mybatis, 簡單一句話相對hibernate而言,純sql的可控性高太多。

  另外,spring boot學到現在,發現其簡化的spring配置不是一點兩點那么簡單。就像用注解形式的mybatis,spring boot中都可以不需要任何手動配置,因為在mybatis.jar中有一套自動配置。

  那么就完全省去了配置的麻煩(雖然實際開發中這並不關一個初中級開發的事。)

  然后剩下的只是mybatis要怎么用?@Mapper有哪些作用?這些都無關繁瑣的配置,而是實際開發要用到的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM