MyBatis使用注解開(kāi)發(fā)和無(wú)主配置文件開(kāi)發(fā)的情況
MyBatis使用注解開(kāi)發(fā)時(shí)就不在需要和接口對(duì)應(yīng)的映射文件了
主要有以下幾個(gè)注解
@Select() @Insert @Update() @Delete()
代碼演示
項(xiàng)目結(jié)構(gòu):
數(shù)據(jù)庫(kù)表設(shè)計(jì)
實(shí)體類
User
public class User implements Serializable { private long userId; private String userName; private Date birthday; private String sex; private String address; getter setter toString
主配置文件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> <properties resource="db.properties"/> <!--開(kāi)啟駝峰命名--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--起別名 typeAliases--> <typeAliases> <package name="com.codeyancy.cn.entity"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!--包掃描--> <package name="com.codeyancy.cn.mapper"/> </mappers> </configuration>
db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/web_test?characterEncoding=utf-8 jdbc.username=root jdbc.password=666
mapper接口
public interface UserMapper { /** * 查詢所有用戶信息 */ @Select("select * from user") List<User> findAll(); /** * 根據(jù)id查詢用戶信息 */ @Select("select * from user where user_id=#{userId}") User findById(Integer id); /** * 新增 */ @Insert("insert into user (user_name,birthday,sex,address) values (#{userName},#{birthday},#{sex},#{address})") void insertUser(User user); /** * 修改 */ @Update("update user set user_name=#{userName},birthday=#{birthday},sex=#{sex},address=#{address} where user_id=#{userId}") void updateUser(User user); /** * 刪除 */ @Delete("delete from user where user_id=#{userId}") void deleteUserById(Integer id); /** * 通過(guò)id或者名字模糊查詢 * 多個(gè)參數(shù)查詢方式二:@Param */ @Select("select * from user where user_id=#{id} or user_name like '%${name}%'") List<User> select(@Param("id") Integer id, @Param("name") String name); }
測(cè)試類
Demo
public class Demo { public static void main(String[] args) { String path="mybatis-config.xml"; InputStream resourceAsStream = null; try { resourceAsStream = Resources.getResourceAsStream(path); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //System.out.println(mapper.findAll()); //System.out.println(mapper.findById(1)); /*User user = new User(); user.setUserName("老皮"); user.setBirthday(new Date()); mapper.insertUser(user);*/ /*User user = new User(); user.setUserName("李立林"); user.setBirthday(new Date()); user.setUserId(27); mapper.updateUser(user);*/ //mapper.deleteUserById(27); System.out.println(mapper.select(1, "麻")); sqlSession.close(); try { resourceAsStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
使用注解開(kāi)發(fā)的一些問(wèn)題
如果數(shù)據(jù)庫(kù)字段名和實(shí)體類的屬性名不一致,也不遵循駝峰命名。這種情況下,如果是使用映射文件可以用resultMap來(lái)解決。
但是注解開(kāi)發(fā)也是可以解決的:
* 如果數(shù)據(jù)庫(kù)列名和實(shí)體類屬性名不一致或者沒(méi)有開(kāi)啟駝峰命名,可以使用@Results解決這個(gè)問(wèn)題 * * @Select("sql語(yǔ)句") * @Results({ * @Result(column="",property=""), * @Result(column="",property=""), * @Result(column="",property=""), * }) * * 使用注解也可以一對(duì)一,一對(duì)多 * @Result(column="",property="",one=@One("sql語(yǔ)句")), 一對(duì)一 * @Result(column="",property="",one=@Many("sql語(yǔ)句")), 一對(duì)多
在mybatis的使用中,主配置文件mybatis-config.xml 是十分重要的,那么能不能不使用主配置文件進(jìn)行mybatis開(kāi)發(fā)呢?
可以?。?!
在官網(wǎng)中清楚的指出了可以使用java代碼來(lái)代替xml主配置文件----》如下
嘗試使用java類來(lái)代替主配置文件
MyBatisDemo
/** *使用java類代替mybatis-config.xml主配置文件 */ public class MyBatisDemo { public static void main(String[] args) { //加載db.properties文件方式一 // InputStream resourceAsStream = MyBatisDemo.class.getClassLoader().getResourceAsStream("db.properties"); // Properties properties = new Properties(); // try { // properties.load(resourceAsStream); // } catch (IOException e) { // e.printStackTrace(); // } // String drive = properties.getProperty("jdbc.driverClassName"); // String url = properties.getProperty("jdbc.url"); // String name = properties.getProperty("jdbc.username"); // String pass = properties.getProperty("jdbc.password"); // DataSource dataSource = new PooledDataSource(drive,url,name,pass); //加載db.properties文件方式二(推薦) ResourceBundle bundle = ResourceBundle.getBundle("db"); String drive = bundle.getString("jdbc.driverClassName"); String url = bundle.getString("jdbc.url"); String name = bundle.getString("jdbc.username"); String pass = bundle.getString("jdbc.password"); DataSource dataSource = new PooledDataSource(drive,url,name,pass); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); //開(kāi)啟包掃描 configuration.addMappers("com.codeyancy.cn.mapper"); //開(kāi)啟駝峰命名 configuration.setMapUnderscoreToCamelCase(true); //設(shè)置別名 //configuration.getTypeAliasRegistry().registerAliases("com.codeyancy.cn.entity"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //打印查詢所有 System.out.println(mapper.findAll()); sqlSession.close(); } }
簡(jiǎn)單測(cè)試后,是可以使用的。
到此這篇關(guān)于MyBatis使用注解開(kāi)發(fā)和無(wú)主配置文件開(kāi)發(fā)的情況的文章就介紹到這了,更多相關(guān)MyBatis注解開(kāi)發(fā)無(wú)主配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 基于注解的springboot+mybatis的多數(shù)據(jù)源組件的實(shí)現(xiàn)代碼
- MybatisPlus 不修改全局策略和字段注解如何將字段更新為null
- Mybatis常見(jiàn)注解有哪些(總結(jié))
- Mybatis注解增刪改查的實(shí)例代碼
- 解決MyBatis @param注解參數(shù)類型錯(cuò)誤異常的問(wèn)題
- 詳解mybatis @SelectProvider 注解
- mybatis3使用@Select等注解實(shí)現(xiàn)增刪改查操作
- MyBatis注解方式之@Update/@Delete使用詳解
- mybatis省略@Param注解操作
- 如何簡(jiǎn)單使用mybatis注解
相關(guān)文章
Spring 報(bào)錯(cuò):元素 "context:component-scan" 的前綴 "context" 未綁定的問(wèn)題解決
這篇文章主要介紹了Spring 報(bào)錯(cuò):元素 "context:component-scan" 的前綴 "context" 未綁定的問(wèn)題解決的相關(guān)資料,需要的朋友可以參考下2016-11-11詳解Java設(shè)計(jì)模式編程中的訪問(wèn)者模式
這篇文章主要介紹了Java設(shè)計(jì)模式編程中的訪問(wèn)者模式,訪問(wèn)者模式的合理利用可以避免項(xiàng)目中出現(xiàn)大量重復(fù)的代碼,需要的朋友可以參考下2016-02-02Java實(shí)戰(zhàn)權(quán)限管理系統(tǒng)的實(shí)現(xiàn)流程
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SpringBoot+MyBatis+AOP+LayUI+Mysql實(shí)現(xiàn)一個(gè)權(quán)限管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2022-01-01Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶鎖定功能
當(dāng)用戶多次登錄失敗的時(shí)候,我們應(yīng)該將賬戶鎖定,等待一定的時(shí)間之后才能再次進(jìn)行登錄操作。今天小編給大家分享Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶鎖定功能,感興趣的朋友一起看看吧2019-11-11解決java junit單元測(cè)試@Test報(bào)錯(cuò)的問(wèn)題
今天小編就為大家分享一篇解決java junit單元測(cè)試@Test報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11詳解如何在SpringBoot項(xiàng)目中使用全局異常處理
在完整的項(xiàng)目開(kāi)發(fā)中,異常的出現(xiàn)幾乎是無(wú)法避免的;如果凡是有可能出現(xiàn)異常的地方,我們都手動(dòng)的使用try-catch將其捕獲的話,會(huì)使得代碼顯得十分臃腫并且后期不好維護(hù)。本文介紹了pringBoot項(xiàng)目中使用全局異常處理的方法,需要的可以參考一下2022-10-10IDEA 程序包不存在,找不到符號(hào)但是明明存在對(duì)應(yīng)的jar包(問(wèn)題分析及解決方案)
這篇文章主要介紹了IDEA 程序包不存在,找不到符號(hào)但是明明存在對(duì)應(yīng)的jar包 的解決方案,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08