IDEA中使用MyBatis(基礎)


項目骨架圖

一:使用IDEA創業Maven項目並在pom.xml中導入使用mybatis的相關依賴

   

<dependencies>
  <!--單元測試-->
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<!--數據庫驅動-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

<!--mybatis驅動 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency>

二:編寫(mysql)數據庫配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/數據庫名稱?useUniCode=true&characterEncoding=utf-8
jdbc.username=賬號
jdbc.password=密碼

 

三:編寫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="jdbc.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>
<!--導入跟接口對應的XML文件-->
<mappers> <mapper resource="com/yjc/dao/IUserDao.xml"/> </mappers> </configuration>

四:在接口中編寫需要實現的方法(實體類在最后)

package com.yjc.dao;
import com.yjc.entity.User;
import java.util.List;
public interface IUserDao {
   public int getByUser();//查詢用戶數量
   public List<User> getUser(String name);//查詢所有用戶信息
   public int insertUser(User user);//新增用戶
   public  int updateUser(User user);//修改用戶信息
   public  int deleteUser(Integer id);//刪除用戶
}

五:編寫和接口相互映射的XML文件(文件名應與接口名相同)

<?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.yjc.dao.IUserDao"> //namespace指向相應的接口地址
    <select id="getByUser">    //id值與接口中的方法名相同
        SELECT count(1) FROM smbms_user
    </select>
   <select id="getUser"  resultType="com.yjc.entity.User">
        SELECT * FROM smbms_user
    </select>
    <insert id="insertUser"  parameterType="com.yjc.entity.User" >
        INSERT INTO smbms_user VALUES (DEFAULT,#{userCode},#{userName},#{userPassword},#{gender},#{birthday},#{phone},#{address},#{userRole},#{createdBy},#{creationDate},#{modifyBy},#{modifyDate})
    </insert>
    <update id="updateUser" parameterType="com.yjc.entity.User" >
        UPDATE smbms_user SET userName=#{userName} WHERE id=#{id}
    </update>
    <delete id="deleteUser">
            DELETE FROM smbms_user WHERE id=#{_parameter}
    </delete>
</mapper>

parameterType為參數類型,基本數據類型可以省略,

resultType為返回值類型,增刪改默認返回int類型數據(代表受影響的行數)

六:變成測試類進行數據測試

 @Test
    public void testone(){

        try {String resource="mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);//加載核心配置文件
            SqlSessionFactory factory =new SqlSessionFactoryBuilder().build(is); //獲得工廠對象
            int count =0;
            SqlSession sqlSession=factory.openSession();  //獲取核心對象
            count =sqlSession.selectOne("getByUser");
            List<User> user=sqlSession.selectList("getUser");
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat();
            Date date=new Date();
            User user1=new User("yangjinchuan","天雁","123456",2,date,"1361001001","五道口",2,1,date,1,date);
          sqlSession.insert("insertUser", user1);
         
            User user2=new User();
            user2.setUserName("天雁");
            user2.setId(1);
            int updateUser = sqlSession.update("updateUser", user2);
            sqlSession.commit();
            System.out.println(updateUser);*/
            sqlSession.delete("deleteUser",31);
           sqlSession.commit();  //修改數據庫操作需要驚喜手動的事務提交(增刪改)
            sqlSession.close();  //需要關閉sqlSession對象釋放資源
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

實體類

package com.yjc.entity;
import java.util.Date;

/**
 * smbms_user 實體類
 * @author liangzz
 * @date2019-09-24 09:02
 */

public class User {
  /**主鍵ID**/
 private Integer id;
  /**用戶編碼**/
 private String userCode;
  /**用戶名稱**/
 private String userName;

    public User() {
    }

    public User(String userCode, String userName, String userPassword, Integer gender, Date birthday, String phone, String address, Integer userRole, Integer createdBy, Date creationDate, Integer modifyBy, Date modifyDate) {
        this.userCode = userCode;
        this.userName = userName;
        this.userPassword = userPassword;
        this.gender = gender;
        this.birthday = birthday;
        this.phone = phone;
        this.address = address;
        this.userRole = userRole;
        this.createdBy = createdBy;
        this.creationDate = creationDate;
        this.modifyBy = modifyBy;
        this.modifyDate = modifyDate;
    }

    /**用戶密碼**/
 private String userPassword;
  /**性別(1:女、 2:男)**/
 private Integer gender;
  /**出生日期**/
 private Date birthday;
  /**手機**/
 private String phone;
  /**地址**/
 private String address;
  /**用戶角色(取自角色表-角色id)**/
 private Integer userRole;
  /**創建者(userId)**/
 private Integer createdBy;
  /**創建時間**/
 private Date creationDate;
  /**更新者(userId)**/
 private Integer modifyBy;
  /**更新時間**/
 private Date modifyDate;

 public void setId(Integer id){
     this.id=id;
 }

 public Integer getId(){
     return id;
 }

 public void setUserCode(String userCode){
     this.userCode=userCode;
 }

 public String getUserCode(){
     return userCode;
 }

 public void setUserName(String userName){
     this.userName=userName;
 }

 public String getUserName(){
     return userName;
 }

 public void setUserPassword(String userPassword){
     this.userPassword=userPassword;
 }

 public String getUserPassword(){
     return userPassword;
 }

 public void setGender(Integer gender){
     this.gender=gender;
 }

 public Integer getGender(){
     return gender;
 }

 public void setBirthday(Date birthday){
     this.birthday=birthday;
 }

 public Date getBirthday(){
     return birthday;
 }

 public void setPhone(String phone){
     this.phone=phone;
 }

 public String getPhone(){
     return phone;
 }

 public void setAddress(String address){
     this.address=address;
 }

 public String getAddress(){
     return address;
 }

 public void setUserRole(Integer userRole){
     this.userRole=userRole;
 }

 public Integer getUserRole(){
     return userRole;
 }

 public void setCreatedBy(Integer createdBy){
     this.createdBy=createdBy;
 }

 public Integer getCreatedBy(){
     return createdBy;
 }

 public void setCreationDate(Date creationDate){
     this.creationDate=creationDate;
 }

 public Date getCreationDate(){
     return creationDate;
 }

 public void setModifyBy(Integer modifyBy){
     this.modifyBy=modifyBy;
 }

 public Integer getModifyBy(){
     return modifyBy;
 }

 public void setModifyDate(Date modifyDate){
     this.modifyDate=modifyDate;
 }

 public Date getModifyDate(){
     return modifyDate;
 }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userCode='" + userCode + '\'' +
                ", userName='" + userName + '\'' +
                ", userPassword='" + userPassword + '\'' +
                ", gender=" + gender +
                ", birthday=" + birthday +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                ", userRole=" + userRole +
                ", createdBy=" + createdBy +
                ", creationDate=" + creationDate +
                ", modifyBy=" + modifyBy +
                ", modifyDate=" + modifyDate +
                '}';
    }
}

初學MyBatis,如有不便,請多擔待,MyBatis代碼后續還可以進行簡化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM