MyBatis使用注解開發(fā)和無主配置文件開發(fā)的情況
MyBatis使用注解開發(fā)時就不在需要和接口對應(yīng)的映射文件了
主要有以下幾個注解
@Select() @Insert @Update() @Delete()
代碼演示
項目結(jié)構(gòu):
數(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"/> <!--開啟駝峰命名--> <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); /** * 通過id或者名字模糊查詢 * 多個參數(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); }
測試類
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(); } } }
使用注解開發(fā)的一些問題
如果數(shù)據(jù)庫字段名和實體類的屬性名不一致,也不遵循駝峰命名。這種情況下,如果是使用映射文件可以用resultMap來解決。
但是注解開發(fā)也是可以解決的:
* 如果數(shù)據(jù)庫列名和實體類屬性名不一致或者沒有開啟駝峰命名,可以使用@Results解決這個問題 * * @Select("sql語句") * @Results({ * @Result(column="",property=""), * @Result(column="",property=""), * @Result(column="",property=""), * }) * * 使用注解也可以一對一,一對多 * @Result(column="",property="",one=@One("sql語句")), 一對一 * @Result(column="",property="",one=@Many("sql語句")), 一對多
在mybatis的使用中,主配置文件mybatis-config.xml 是十分重要的,那么能不能不使用主配置文件進行mybatis開發(fā)呢?
可以!??!
在官網(wǎng)中清楚的指出了可以使用java代碼來代替xml主配置文件----》如下
嘗試使用java類來代替主配置文件
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); //開啟包掃描 configuration.addMappers("com.codeyancy.cn.mapper"); //開啟駝峰命名 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(); } }
簡單測試后,是可以使用的。
到此這篇關(guān)于MyBatis使用注解開發(fā)和無主配置文件開發(fā)的情況的文章就介紹到這了,更多相關(guān)MyBatis注解開發(fā)無主配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring 報錯:元素 "context:component-scan" 的前綴 "context" 未綁定的問題解決
這篇文章主要介紹了Spring 報錯:元素 "context:component-scan" 的前綴 "context" 未綁定的問題解決的相關(guān)資料,需要的朋友可以參考下2016-11-11Java實戰(zhàn)權(quán)限管理系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SpringBoot+MyBatis+AOP+LayUI+Mysql實現(xiàn)一個權(quán)限管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01Spring Security實現(xiàn)多次登錄失敗后賬戶鎖定功能
當(dāng)用戶多次登錄失敗的時候,我們應(yīng)該將賬戶鎖定,等待一定的時間之后才能再次進行登錄操作。今天小編給大家分享Spring Security實現(xiàn)多次登錄失敗后賬戶鎖定功能,感興趣的朋友一起看看吧2019-11-11IDEA 程序包不存在,找不到符號但是明明存在對應(yīng)的jar包(問題分析及解決方案)
這篇文章主要介紹了IDEA 程序包不存在,找不到符號但是明明存在對應(yīng)的jar包 的解決方案,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08