最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MyBatis使用注解開發(fā)和無(wú)主配置文件開發(fā)的情況

 更新時(shí)間:2021年03月15日 10:45:23   作者:愛喝椰汁的木木  
這篇文章主要介紹了MyBatis使用注解開發(fā)和無(wú)主配置文件開發(fā)的情況,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

MyBatis使用注解開發(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"/>

 <!--開啟駝峰命名-->
 <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();
  }
 }
}

使用注解開發(fā)的一些問(wèn)題

如果數(shù)據(jù)庫(kù)字段名和實(shí)體類的屬性名不一致,也不遵循駝峰命名。這種情況下,如果是使用映射文件可以用resultMap來(lái)解決。

但是注解開發(fā)也是可以解決的:

* 如果數(shù)據(jù)庫(kù)列名和實(shí)體類屬性名不一致或者沒有開啟駝峰命名,可以使用@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開發(fā)呢?

可以?。。?/code>

在官網(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);
  //開啟包掃描
  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();
 }
}

簡(jiǎn)單測(cè)試后,是可以使用的。

到此這篇關(guān)于MyBatis使用注解開發(fā)和無(wú)主配置文件開發(fā)的情況的文章就介紹到這了,更多相關(guān)MyBatis注解開發(fā)無(wú)主配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

柘城县| 江门市| 永安市| 怀仁县| 陵水| 康平县| 开封市| 沛县| 武定县| 蕲春县| 鄢陵县| 房产| 三明市| 庆阳市| 松滋市| 台北县| 浦城县| 德格县| 保亭| 楚雄市| 九龙县| 哈尔滨市| 龙川县| 江津市| 万年县| 安顺市| 吴忠市| 怀来县| 云龙县| 邹平县| 普格县| 潜山县| 东辽县| 裕民县| 阿勒泰市| 本溪市| 丰顺县| 安阳市| 广西| 淳化县| 宁津县|