mybatis3開始支持java注解永品,使用java注解可以替代xml配置文件,簡(jiǎn)化代碼时迫。下面來看一下怎么在spring boot中使用mybatis注解娇昙。
1 使用mybatis注解需要的配置。如下面的代碼所示剥哑,使用@MapperScan來掃描注冊(cè)mybatis數(shù)據(jù)庫(kù)接口類硅则,其中basePackages屬性表明接口類所在的包,sqlSessionTemplateRef表明接口類使用的SqlSessionTemplate株婴。如果項(xiàng)目需要配置兩個(gè)數(shù)據(jù)庫(kù)怎虫,@MapperScan也需要分別配置。
@Configuration
@MapperScan(basePackages="com.boot.test.mapper",sqlSessionTemplateRef="sqlSessionTemplate")
public class DatabaseConfig {
@Bean
@ConfigurationProperties(prefix = "test.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2 mybatis注解介紹
mybatis3支持多個(gè)java注解困介,下面介紹幾個(gè)基本的注解大审。
@Insert
@Insert("insert into t_user(name,age,gender) values (#{name},#{age},#{gender})")
public int addUser(User user) throws DataAccessException;
如上面的代碼所示,使用@Insert注解可以在()中直接寫sql語(yǔ)句座哩,傳參可以用#{}實(shí)現(xiàn)徒扶,其中name字段名直接對(duì)應(yīng)User類中的name字段,腫么樣根穷,有沒有很直觀方便:)
@Select
@Select("select age,gender from t_user where name={name}")
public User queryUser(String name) throws DataAccessException;
@Select 注解所查詢出的字段可以直接綁定到User類中對(duì)應(yīng)的字段中酷愧,由于在類中可以import對(duì)應(yīng)的類驾诈,免去了在xml中配置結(jié)果集的麻煩。
@SelectKey
@SelectKey(statement = "select max(id) from t_id", before = true, resultType = long.class, keyProperty = "id")
@Insert("insert into t_user(id,name,age,gender) values (#{id},#{name},#{age},#{gender})")
public int addUser(User user) throws DataAccessException;
@SelectKey注解用于查詢一下需要的前置字段溶浴,如上面的代碼所示先查出id字段的值乍迄,然后插入到t_user表中,一般配合@Insert和@Update
注解使用士败。
版本說明:spring boot: 1.4.0.RELEASE ? mybatis: 3.2.3 ?mybatis-spring: 1.2.2
參考文檔:http://www.mybatis.org/mybatis-3/java-api.html 參見Mapper Annotations 部分