您好,登錄后才能下訂單哦!
這篇文章給大家介紹Spring boot 中怎么配置mybatis,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
1 添加相關(guān)maven文件
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
完整的pom包這里就不貼了,大家直接看源碼
2、application.properties 添加數(shù)據(jù)庫和mybatis配置
mybatis.type-aliases-package=com.neo.entity //對(duì)應(yīng)實(shí)體類的包名 spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = root
springboot會(huì)自動(dòng)加載spring.datasource.*相關(guān)配置,數(shù)據(jù)源就會(huì)自動(dòng)注入到sqlSessionFactory中,sqlSessionFactory會(huì)自動(dòng)注入到Mapper中,對(duì)了你一切都不用管了,直接拿起來使用就行了。
在啟動(dòng)類中添加對(duì)mapper包掃描@MapperScan
@SpringBootApplication @MapperScan("com.neo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
或者直接在Mapper類上面添加注解@Mapper,建議使用上面那種,不然每個(gè)mapper加個(gè)注解也挺麻煩的
3、開發(fā)Mapper
第三步是最關(guān)鍵的一塊,sql生產(chǎn)都在這里
public interface UserMapper { @Select("SELECT * FROM users") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) List<UserEntity> getAll(); @Select("SELECT * FROM users WHERE id = #{id}") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) UserEntity getOne(Long id); @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})") void insert(UserEntity user); @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}") void update(UserEntity user); @Delete("DELETE FROM users WHERE id =#{id}") void delete(Long id); }
為了更接近生產(chǎn)我特地將user_sex、nick_name兩個(gè)屬性在數(shù)據(jù)庫加了下劃線和實(shí)體類屬性名不一致,另外user_sex使用了枚舉
@Select 是查詢類的注解,所有的查詢均使用這個(gè)
@Result 修飾返回的結(jié)果集,關(guān)聯(lián)實(shí)體類屬性和數(shù)據(jù)庫字段一一對(duì)應(yīng),如果實(shí)體類屬性和數(shù)據(jù)庫屬性名保持一致,就不需要這個(gè)屬性來修飾。
@Insert 插入數(shù)據(jù)庫使用,直接傳入實(shí)體類會(huì)自動(dòng)解析屬性到對(duì)應(yīng)的值
@Update 負(fù)責(zé)修改,也可以直接傳入對(duì)象
@delete 負(fù)責(zé)刪除
了解更多屬性參考這里
注意,使用#符號(hào)和$符號(hào)的不同:
// This example creates a prepared statement, something like select * from teacher where name = ?; @Select("Select * from teacher where name = #{name}") Teacher selectTeachForGivenName(@Param("name") String name); // This example creates n inlined statement, something like select * from teacher where name = 'someName'; @Select("Select * from teacher where name = '${name}'") Teacher selectTeachForGivenName(@Param("name") String name);
4、使用
上面三步就基本完成了相關(guān)dao層開發(fā),使用的時(shí)候當(dāng)作普通的類注入進(jìn)入就可以了
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest { @Autowired private UserMapper UserMapper; @Test public void testInsert() throws Exception { UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN)); UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN)); UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN)); Assert.assertEquals(3, UserMapper.getAll().size()); } @Test public void testQuery() throws Exception { List<UserEntity> users = UserMapper.getAll(); System.out.println(users.toString()); } @Test public void testUpdate() throws Exception { UserEntity user = UserMapper.getOne(3l); System.out.println(user.toString()); user.setNickName("neo"); UserMapper.update(user); Assert.assertTrue(("neo".equals(UserMapper.getOne(3l).getNickName()))); } }
源碼中controler層有完整的增刪改查,這里就不貼了
極簡(jiǎn)xml版本
極簡(jiǎn)xml版本保持映射文件的老傳統(tǒng),優(yōu)化主要體現(xiàn)在不需要實(shí)現(xiàn)dao的是實(shí)現(xiàn)層,系統(tǒng)會(huì)自動(dòng)根據(jù)方法名在映射文件中找對(duì)應(yīng)的sql.1、application.yml 配置
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/用哪個(gè)數(shù)據(jù)庫?useUnicode=true&characterEncoding=utf-8 username: 用戶名 password: 密碼 server: port: 8080 mybatis: config-location: classpath:config/mybatis-config.xml mapper-locations: classpath:mapper/*.xml MyBatis 配置項(xiàng)解讀: config-location:指定 MyBatis 主配置文件的位置 mapper-locations:指定 mapper 文件的位置。如果在項(xiàng)目中你的 mapper 文件是按目錄來放置,那么對(duì)應(yīng)的配置就變成:mapper-locations: classpath:mapper/*/*.xml
這時(shí)候假設(shè)我們的 resources 結(jié)構(gòu)是這樣的:
|-resources |--config |---application.yml |---mybatis-config.xml |--mapper |---CityMapper.xml
3、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.mybatis.domain"/> </typeAliases> <!--<mappers>--> <!--<mapper resource="sample/mybatis/mapper/CityMapper.xml"/>--> <!--<mapper resource="sample/mybatis/mapper/HotelMapper.xml"/>--> <!--</mappers>--> </configuration>
這個(gè)配置見仁見智,在它里面我就配置了一個(gè)
typeAliases
。不了解的同學(xué)可以移步文檔查看相關(guān)解釋。
你也可以把 mapper 配置在此處,有多少個(gè) mapper 就配置多少次,當(dāng)然,我們已經(jīng)在 application.yml中批量指定了,很方便,就不用在此處一個(gè)個(gè)寫。
2、添加User的映射文件
<mapper namespace="com.neo.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" > <id column="id" property="id" jdbcType="BIGINT" /> <result column="userName" property="userName" jdbcType="VARCHAR" /> <result column="passWord" property="passWord" jdbcType="VARCHAR" /> <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/> <result column="nick_name" property="nickName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, userName, passWord, user_sex, nick_name </sql> <select id="getAll" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM users </select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM users WHERE id = #{id} </select> <insert id="insert" parameterType="com.neo.entity.UserEntity" > INSERT INTO users (userName,passWord,user_sex) VALUES (#{userName}, #{passWord}, #{userSex}) </insert> <update id="update" parameterType="com.neo.entity.UserEntity" > UPDATE users SET <if test="userName != null">userName = #{userName},</if> <if test="passWord != null">passWord = #{passWord},</if> nick_name = #{nickName} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM users WHERE id =#{id} </delete> </mapper>
其實(shí)就是把上個(gè)版本中mapper的sql搬到了這里的xml中了
3、編寫Dao層的代碼
public interface UserMapper { List<UserEntity> getAll(); UserEntity getOne(Long id); void insert(UserEntity user); void update(UserEntity user); void delete(Long id); }
關(guān)于Spring boot 中怎么配置mybatis就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。