程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java經由過程MyBatis框架對MySQL數據停止增刪查改的根本辦法

Java經由過程MyBatis框架對MySQL數據停止增刪查改的根本辦法

編輯:關於JAVA

Java經由過程MyBatis框架對MySQL數據停止增刪查改的根本辦法。本站提示廣大學習愛好者:(Java經由過程MyBatis框架對MySQL數據停止增刪查改的根本辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java經由過程MyBatis框架對MySQL數據停止增刪查改的根本辦法正文


1. 查詢

除單筆記錄的查詢,這裡我們來測驗考試查詢一組記載。

IUserMapper接口添加上面辦法:

List<User> getUsers(String name); 

在User.xml中添加:

<resultMap type="User" id="userList"><!-- type為前往列表元素的類全名或別號 --> 
  <id column="id" property="id" /> 
  <result column="name" property="name" /> 
  <result column="age" property="age" /> 
  <result column="address" property="address" /> 
</resultMap> 
 
<select id="getUsers" parameterType="string" resultMap="userList"><!-- resultMap為下面界說的User列表 --> 
  select * from `user` where name like #{name} 
</select> 

測試辦法:

@Test 
public void queryListTest() { 
  SqlSession session = sqlSessionFactory.openSession(); 
  try { 
    IUserMapper mapper = session.getMapper(IUserMapper.class); 
    List<User> users = mapper.getUsers("%a%"); // %在sql裡代表隨意率性個字符。 
    for (User user : users) { 
      log.info("{}: {}", user.getName(), user.getAddress()); 
    } 
  } finally { 
    session.close(); 
  } 
} 

假如聯表查詢,前往的是復合對象,須要用association症結字來處置。
如User揭橥Article,每一個用戶可以揭橥多個Article,他們之間是一對多的關系。

(1) 創立Article表,並拔出測試數據:

-- Drop the table if exists 
DROP TABLE IF EXISTS `Article`; 
 
-- Create a table named 'Article' 
CREATE TABLE `Article` ( 
  `id` int NOT NULL AUTO_INCREMENT, 
  `user_id` int NOT NULL, 
  `title` varchar(100) NOT NULL, 
  `content` text NOT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 
 
-- Add several test records 
INSERT INTO `article` 
VALUES 
('1', '1', 'title1', 'content1'), 
('2', '1', 'title2', 'content2'), 
('3', '1', 'title3', 'content3'), 
('4', '1', 'title4', 'content4'); 

(2) com.john.hbatis.model.Article類:

public class Article { 
  private int id; 
  private User user; 
  private String title; 
  private String content; 
  // Getters and setters are omitted 
} 

(3) 在IUserMapper中添加:

List<Article> getArticlesByUserId(int id); 

(4) 在User.xml中添加:

<resultMap type="com.john.hbatis.model.Article" id="articleList"> 
  <id column="a_id" property="id" /> 
  <result column="title" property="title" /> 
  <result column="content" property="content" /> 
   
  <association property="user" javaType="User"><!-- user屬性映照到User類 --> 
    <id column="id" property="id" /> 
    <result column="name" property="name" /> 
    <result column="address" property="address" /> 
  </association> 
</resultMap> 
 
<select id="getArticlesByUserId" parameterType="int" resultMap="articleList"> 
  select u.id, u.name, u.age, u.address, a.id a_id, a.title, a.content 
  from article a 
  inner join user u 
  on a.user_id=u.id and u.id=#{id} 
</select> 

(5)測試辦法:

@Test 
public void getArticlesByUserIdTest() { 
  SqlSession session = sqlSessionFactory.openSession(); 
  try { 
    IUserMapper mapper = session.getMapper(IUserMapper.class); 
    List<Article> articles = mapper.getArticlesByUserId(1); 
    for (Article article : articles) { 
      log.info("{} - {}, author: {}", article.getTitle(), article.getContent(), article.getUser().getName()); 
    } 
  } finally { 
    session.close(); 
  } 
} 

附:
除在association標簽內界說字段和屬性的映照外,還可以重用User的resultMap:

<association property="user" javaType="User" resultMap="userList" /> 

2. 新增

IUserMapper接口添加上面辦法:

int addUser(User user); 

User.xml添加:

<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"><!-- useGeneratedKeys指定myBatis應用數據庫主動生成的主鍵,並填充到keyProperty指定的屬性上。假如未指定,前往對象拿不到生成的值 --> 
  insert into user(name,age,address) values(#{name},#{age},#{address}) 
</insert> 

測試辦法:

@Test 
public void addUserTest() { 
  User user = new User("Lucy", 102, "Happy District"); 
  SqlSession session = sqlSessionFactory.openSession(); 
  try { 
    IUserMapper mapper = session.getMapper(IUserMapper.class); 
    int affectedCount = mapper.addUser(user); 
    session.commit(); // 默許為不主動提交。挪用session.getConnection().getAutoCommit()檢查 
    log.info("{} new record was inserted successfully whose id: {}", affectedCount, user.getId()); 
  } finally { 
    session.close(); 
  } 
} 

3. 更新

接口添加辦法:

int updateUser(User user); 

User.xml添加:

<update id="updateUser" parameterType="User"> 
  update `user` set name=#{name}, age=#{age}, address=#{address} 
  where id=#{id} 
</update> 

測試辦法:

@Test 
public void updateUserTest() { 
  SqlSession session = sqlSessionFactory.openSession(); 
  try { 
    IUserMapper mapper = session.getMapper(IUserMapper.class); 
    User user = mapper.getUserById(8); 
    user.setAddress("Satisfied District"); 
    int affectedCount = mapper.updateUser(user); // 除要修正的屬性外,user的其它屬性也要賦值,不然這些屬性會被數據庫更新為初始值(null或0等),可以先查詢一次,但如許會增長和數據庫不用要的交互。前面的前提斷定能防止此成績。 
    log.info("Affected count: {}", affectedCount); 
    session.commit(); 
  } finally { 
    session.close(); 
  } 
} 

 4. 刪除

接口添加辦法:

int deleteUser(int id); 

User.xml添加:

<delete id="deleteUser" parameterType="int"> 
  delete from `user` where id=#{id} 
</delete> 

測試辦法:

@Test 
public void deleteUserTest() { 
  SqlSession session = sqlSessionFactory.openSession(); 
  try { 
    IUserMapper mapper = session.getMapper(IUserMapper.class); 
    int affectedCount = mapper.deleteUser(8); 
    log.info("Affected count: {}", affectedCount); 
    session.commit(); 
  } finally { 
    session.close(); 
  } 
} 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved