一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Java+MyBatis+MySQL開發環境搭建流程詳解

Java+MyBatis+MySQL開發環境搭建流程詳解

2020-05-08 11:46czj4451 JAVA教程

Java的MyBatis框架提供了強大的數據庫操作支持,這里我們先在本地的開發環境中上手,來看一下Java+MyBatis+MySQL開發環境搭建流程詳

主要搭建過程

1. pom.xml文件中加入mybatis和數據庫依賴,這里使用mysql:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<properties>
 <mybatis.version>3.2.3</mybatis.version>
 <mysql.version>5.1.26</mysql.version>
 <slf4j.api.version>1.7.5</slf4j.api.version>
 <testng.version>6.8.7</testng.version>
</properties>
 
<dependencies>
 <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>${mybatis.version}</version>
 </dependency>
 <!-- Database driver -->
 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>${mysql.version}</version>
 </dependency>
 <!-- mybatis啟動要加載log4j -->
 <dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>${slf4j.api.version}</version>
 </dependency>
 <!-- Test -->
 <dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>${testng.version}</version>
 </dependency>
</dependencies>


2. 在類路徑下創建mybatis的配置文件Configuration.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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><!-- 別名 -->
    <typeAlias alias="User" type="com.john.hbatis.model.User" />
  </typeAliases>
   
  <environments default="development">
   <environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED"><!-- 數據源 -->
      <property name="driver" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/hbatis" />
      <property name="username" value="root" />
      <property name="password" value="123456" />
    </dataSource>
   </environment>
  </environments>
   
  <mappers><!-- ORM映射文件 -->
    <mapper resource="com/john/hbatis/model/User.xml" />
  </mappers>
 </configuration>


3. 執行創建數據庫和表的sql:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- Create the database named 'hbatis'.
-- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible.
CREATE DATABASE IF NOT EXISTS `hbatis`
DEFAULT CHARACTER SET = `UTF8`;
 
-- Create a table named 'User'
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
-- Insert a test record
Insert INTO `user` VALUES ('1', 'john', '120', 'hangzhou,westlake');


4. com.john.hbatis.model.User類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class User {
  private int id;
  private String name;
  private String age;
  private String address;
  // Getters and setters are omitted
 
  // 如果有帶參數的構造器,編譯器不會自動生成無參構造器。當查詢需要返回對象時,ORM框架用反射來調用對象的無參構造函數,導致異常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.<init>()
  // 這時需要明確寫出:
  public User() {
  }
 
  public User(int id, String address) {
    this.id = id;
    this.address = address;
  }
 
  public User(String name, int age, String address) {
    this.name = name;
    this.age = age;
    this.address = address;
  }
}

com/john/hbatis/model路徑下的User.xml

?
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.john.hbatis.model.UserMapper">
  <select id="getUserById" parameterType="int" resultType="User">
    select * from `user` where id = #{id}
  </select>
</mapper>


5. 測試類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MyBatisBasicTest {
  private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class);
  private static SqlSessionFactory sqlSessionFactory;
   
  private static Reader reader;
   
  @BeforeClass
  public static void initial() {
    try {
      reader = Resources.getResourceAsReader("Configuration.xml");
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    } catch (IOException e) {
      log.error("Error thrown while reading the configuration: {}", e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          log.error("Error thrown while closing the reader: {}", e);
        }
      }
    }
  }
   
  @Test
  public void queryTest() {
    SqlSession session = sqlSessionFactory.openSession();
    User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);
    log.info("{}: {}", user.getName(), user.getAddress());
  }
}

以接口方式交互數據
上面的環境搭建是采用SqlSession的通用方法并強制轉換的方式,存在著轉換安全的問題:

?
1
User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);

可以采用接口加sql語句的方式來解決,sql語句理解為是接口的實現:

1. 新建接口類:

?
1
2
3
4
5
6
7
package com.john.hbatis.mapper;
 
import com.john.hbatis.model.User;
 
public interface IUserMapper {
  User getUserById(int id);
}

2. 修改User.xml文件,確保namespace屬性值和接口的全限定名相同,且id屬性值和接口方法名相同:

?
1
2
<mapper namespace="com.john.hbatis.mapper.IUserMapper">
  <select id="getUserById"

3. 在MyBatisBasicTest類中添加測試方法:

?
1
2
3
4
5
6
7
@Test
public void queryInInterfaceWayTest() {
  SqlSession session = sqlSessionFactory.openSession();
  IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,報org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry異常。
  User user = mapper.getUserById(1);
  log.info("{}: {}", user.getName(), user.getAddress());
}

附:
上面的實現是把sql語句放在XML文件中,并通過一定的約束來保證接口能夠在XML中找到對應的SQL語句;
還有一種方式是通過接口+注解SQL方式來交互數據:

1. 新建接口類:

?
1
2
3
4
5
6
7
8
9
10
package com.john.hbatis.mapper;
 
import org.apache.ibatis.annotations.Select;
 
import com.john.hbatis.model.User;
 
public interface IUserMapper2 {
  @Select({ "select * from `user` where id = #{id}" })
  User getUserById(int id);
}

2. 在Configuration.xml文件中加入:

?
1
2
3
<mappers>
  <mapper class="com.john.hbatis.mapper.IUserMapper2" />
</mappers>

或在初始化語句中加入:

?
1
sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);

3. 相應修改上面的測試方法:

?
1
IUserMapper2 mapper = session.getMapper(IUserMapper2.class);

 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美精品一区二区三区免费 | 国产一区二区视频在线观看 | 成人免费毛片一区二区三区 | 成人性生交小说免费看 | 国产精品制服丝袜白丝www | 国产精品国产色综合色 | 国产欧美视频一区二区三区 | 男人含玉势出嫁束器 | 欧美日韩高清完整版在线观看免费 | 美女免费观看一区二区三区 | 午夜影院网站 | 波多野结衣同性系列698 | 精品在线免费播放 | 日本中文字幕在线精品 | 午夜AV内射一区二区三区红桃视 | 大jjjj免费看视频 | 欧美老骚 | 色综合久久综合网欧美综合网 | 麻豆视频免费在线观看 | 日本嫩小xxxxhd | 调教肉文 | 国产日韩欧美精品在线 | 香蕉久草在线 | 国产原创一区二区 | 日本视频免费在线观看 | 国产一区日韩二区欧美三 | 免费在线看片网站 | 91人人 | 好男人免费高清在线观看2019 | 亚洲精品在线免费 | 婷婷99视频精品全部在线观看 | 爱情岛论坛自拍永久入口 | 好大好深受不了了快进来 | 午夜伦理:伦理片 | 国产亚洲精品福利在线 | 火影忍者小南裸羞羞漫画 | a v在线男人的天堂观看免费 | coolgay男男gayxxx chinese壮直男gay老年人 chinese野外gay军人 | 韩国甜性涩爱免费观看 | 午夜福利在线观看6080 | 青青久久久国产线免观 |