程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Mybatis學習(一),Mybatis學習(

Mybatis學習(一),Mybatis學習(

編輯:JAVA綜合教程

Mybatis學習(一),Mybatis學習(


1)先導入pom文件

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Mybatis</groupId>
  <artifactId>com.mybatis</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>com.mybatis Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
  
          <!-- mybatis -->
          <dependency>
               <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- mysql-connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
  
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>com.mybatis</finalName>
  </build>
</project>
View Code

2)創建配置文件

3)數據庫驅動文件:

 

4)為mybatis配置mybatis.cfg.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="config.properties"></properties>
    
    <typeAliases>
         <!-- 別名方式1,一個一個的配置 type中放置的是類的全路徑,alias中放置的是類別名
         <typeAliase type="com.cy.mybatis.beans.UserBean" alias="UserBean"/> -->
         <!-- 別名方式2,自動掃描,將JAVA類的類名作為類的類別名 -->
        <package name="com.mybatis.entity"/>
    </typeAliases>
    <!-- 配置mybatis運行環境 -->
      <environments default="cybatis">
         <environment id="cybatis">
             <!-- type="JDBC" 代表使用JDBC的提交和回滾來管理事務 -->
             <transactionManager type="JDBC" />
             
             <!-- mybatis提供了3種數據源類型,分別是:POOLED,UNPOOLED,JNDI -->
             <!-- POOLED 表示支持JDBC數據源連接池 -->
             <!-- UNPOOLED 表示不支持數據源連接池 -->
             <!-- JNDI 表示支持外部數據源連接池 -->
             <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> 
     
     <mappers>
          <!-- 告知映射文件方式1,一個一個的配置
        <mapper resource="com/cy/mybatis/mapper/UserMapper.xml" class="com.mybatis.mapper.UserMapper"/>-->
        <!-- 告知映射文件方式2,自動掃描包內的Mapper接口與配置文件 -->
         <package name="com/mybatis/mapper"/>
     </mappers>
</configuration>

5)創建數據庫表:

6)編寫實體類:

package com.mybatis.entity;

import java.io.Serializable;

public class User implements Serializable{

    private Integer id;
    private String username;
    private String password;
    private Double account;
    
    public User() {
        super();
    }

    public User(Integer id, String username, String password, Double account) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.account = account;
    }


    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Double getAccount() {
        return account;
    }

    public void setAccount(Double account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
View Code

 

 7)編寫映射的數據訪問接口:

package com.mybatis.mapper;

import com.mybatis.entity.User;

public interface UserMapper {

    
    public int saveUser(User user);
    
    public int updateUser(User user);
    
    public int deleteUser(User user);
    
    public int selectUserById(int id);
    
    public int selectAllUser();
    
}
View Code

 

8)配置數據訪問接口映射xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper">
    <resultMap type="User" id="user">
        <id property="id" column="id" javaType="java.lang.Integer"/>
        <result property="username" column="username" javaType="java.lang.String"/>
        <result property="password" column="password" javaType="java.lang.String"/>
        <result property="account" column="account" javaType="java.lang.Double"/>
    </resultMap>
    
    <insert id="saveUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(username,password,account) values(#{username},#{password},#{account})
    </insert>

</mapper>

 

 

 9)因為沒有與spring進行整合,所以認為提交事務,也並沒有關閉session,(注意)

package com.mybatis.tool;

 
 import java.io.Reader;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
public class DBTools {
    public static SqlSessionFactory sessionFactory;
    
    static{
        try {
            //使用MyBatis提供的Resources類加載mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            //構建sqlSession的工廠
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //創建能執行映射文件中sql的sqlSession
    public static SqlSession getSession(){
        return sessionFactory.openSession();
    }
     
}
View Code

 

10)測試:

package com.mybatis.service;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.tool.DBTools;

public class UserService {

    
    public void save(User user){
        SqlSession session = DBTools.getSession();
        int count = session.getMapper(UserMapper.class).saveUser(user);
        session.commit();
    }
    
    public static void main(String[] args) {
        User user=  new User(null, "彬彬", "123456", 8.0);
        new UserService().save(user);
    }
    
}

 

 

 

 成功,第一階段完成

 

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