Mybatis-就是使用接口+XML映射文件直接操作數據庫


1.1.1. 第一步:導入包

 

 

 

1.1.2. 第二步:創建一個總配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >

<!-- XMLConfigBuilder是總配置文件的構建類 -->

<configuration>

  <!-- 用於配置數據庫的連接參數 ,environments這個標簽可以配置多個數據庫的連接,default表示默認使用的配置-->

  <environments default="default-msql">

  

     <!-- 數據庫的連接參數 Configuration查看參數-->

     <!-- 所有框架的靜態屬性都可以在這個框架的類里面找到,不用死記硬背 -->

     <!-- id:就是一個標識符 -->

     <environment id="default-msql">

        <!-- 事務類型 -->

        <!-- 事務類型有哪些

         JDBC:使用JDBC事務

         MANAGED:不用事務

         -->

        <transactionManager type="JDBC"></transactionManager>

        <!-- 數據源 -->

        <!-- type表示數據庫的類型

           JNDI:使用JNDI獲得數據源.

           POOLED:使用默認的連接池獲得數據源

           UNPOOLED:不用數據源

         

          -->

          <!-- org.apache.ibatis.datasource.pooled.PooledDataSource -->

        <dataSource type="POOLED">

           <!-- 所有的property對應的是一個set方法 -->

           <!-- 四要素 -->

           <property name="driver" value="org.gjt.mm.mysql.Driver"/>

           <property name="url" value="jdbc:mysql://localhost:3306/school"/>

           <property name="username" value="root"/>

           <property name="password" value="123456"/>

        </dataSource>

     </environment>

  </environments>

  <!-- 加載映射文件 -->

  <mappers>

    <!-- class屬性:加載的是使用注解調用方式的接口 -->

    <mapper class="cn.gzsxt.mapper.StudentMapper"/>

  </mappers>

 

</configuration>

 

 

1.1.3. 第三步:創建一個DbUtils,獲得SqlSession操作對象

package cn.lxm.utils;

 

import java.io.IOException;

import java.io.InputStream;

 

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

 

/**

 * 這個一個數據庫連接幫助類,用於獲得操作數據庫的SqlSession對象

 * @author Administrator

 *

 */

public class DbUtils {

 

//1.獲得SqlSessionFactory

 

public static SqlSessionFactory createSqlSessionFactory(){

//1.通過Resources讀取配置文件

try {

//獲得一個總配置文件的輸入流

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

//2.創建一個SqlSessionFactoryBuilder

SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();

//獲得會話工廠

SqlSessionFactory sqlSessionFactory = builder.build(inputStream);

return sqlSessionFactory;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

return null;

}

 

//2.獲得SqlSession

public static SqlSession getSession(){

 

SqlSessionFactory sqlSessionFactory = DbUtils.createSqlSessionFactory();

return sqlSessionFactory.openSession();

}

 

public static void main(String[] args) {

System.out.println(DbUtils.getSession());

}

 

 

}

 

 

 

1.1.4. 第四步:創建一個映射接口+操作的注解

package cn.lxm.mapper;

 

import java.util.List;

 

import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.Update;

 

import cn.lxm.entity.Student;

 

public interface StudentMapper {

 

/**

 * 插入記錄

 * @param entity

 * @return

 */

@Insert(value="INSERT INTO student(AID, SNAME, SEX, BIRTHDAY, AGE) VALUES (#{sid}, #{sname}, #{sex}, #{birthday}, #{age})")

int insert(Student entity);

 

/**

 * 刪除記錄

 * @param sid

 * @return

 */

@Delete(value="DELETE FROM student WHERE SID=#{sid}")

int deleteById(int sid);

 

/**

 * 更新記錄

 * @param entity

 * @return

 */

@Update(value="UPDATE student SET AID=#{aid},SNAME=#{sname},SEX=#{sex},BIRTHDAY=#{birthday},AGE=#{age} WHERE SID=#{sid}")

int update(Student entity);

/**

 * 查詢所有的記錄

 * @return

 */

@Select(value="SELECT * FROM student")

List<Student> findAll();

 

}

 

 

1.創建一個實體類

package cn.lxm.entity;

 

import java.util.Date;

 

//ctrl+shift+y 大寫轉小寫

public class Student {

 

private Integer sid;//int(11) not null auto_increment comment '編號',

private Integer aid;//int(11) null default '0',

private String sname;//varchar(50) null default null comment '姓名',

private String sex;//char(3) null default null comment '性別',

private Date birthday;//date null default null comment '生日',

private Integer age;//int(11) null default null comment '年齡',

public Integer getSid() {

return sid;

}

public void setSid(Integer sid) {

this.sid = sid;

}

public Integer getAid() {

return aid;

}

public void setAid(Integer aid) {

this.aid = aid;

}

public String getSname() {

return sname;

}

public void setSname(String sname) {

System.out.println("-輸出名字-"+sname);

this.sname = sname;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

 

}

 

 

1.1.5. 第五步:測試代碼

package cn.lxm.test;

 

import static org.junit.Assert.*;

 

import java.util.Date;

import java.util.List;

 

import org.apache.ibatis.session.SqlSession;

import org.junit.Test;

 

import cn.lxm.entity.Student;

import cn.lxm.mapper.StudentMapper;

import cn.lxm.utils.DbUtils;

 

public class StudentMapperTest {

 

/* @Test

public void insert() {

try {

//1.獲得操作對象

SqlSession session = DbUtils.getSession();

//2.使用session.獲得映射接口的代理對象,這個代理對象是mybatis通過StudentMapper.xml創建的

StudentMapper studentMapper = session.getMapper(StudentMapper.class);

Student student = new Student();

student.setSname("王五");

student.setSex("男");

//調用接口操作數據庫

studentMapper.insert(student);

//提交

session.commit();

session.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}*/

 

/* @Test

public void deleteById(){

//1.獲得操作對象

SqlSession session = DbUtils.getSession();

//2.使用session.獲得映射接口的代理對象,這個代理對象是mybatis通過StudentMapper.xml創建的

StudentMapper studentMapper = session.getMapper(StudentMapper.class);

int count=studentMapper.deleteById(1);

System.out.println(count);

session.commit();

session.close();

}*/

 

 

/* @Test

public void update(){

//1.獲得操作對象

SqlSession session = DbUtils.getSession();

//2.使用session.獲得映射接口的代理對象,這個代理對象是mybatis通過StudentMapper.xml創建的

StudentMapper studentMapper = session.getMapper(StudentMapper.class);

Student entity=new Student();

entity.setSname("趙六");

entity.setSex("男");

entity.setAge(20);

entity.setBirthday(new Date());

entity.setSid(2);

 

//更新記錄

int count=studentMapper.update(entity);

System.out.println(count);

session.commit();

session.close();

}*/

 

@Test

public void findAll(){

//1.獲得操作對象

SqlSession session = DbUtils.getSession();

//2.使用session.獲得映射接口的代理對象,這個代理對象是mybatis通過StudentMapper.xml創建的

StudentMapper studentMapper = session.getMapper(StudentMapper.class);

List<Student> list = studentMapper.findAll();

for(Student s:list){

System.out.print("姓名:"+s.getSname());

System.out.print(",年齡:"+s.getAge());

System.out.println(",生日:"+s.getBirthday());

}

 

session.commit();

session.close();

}

}

 


免責聲明!

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



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