您的位置:首頁>正文

最基礎的mybatis入門demo

demo結構

資料庫情況 (不會轉sql語句 騷瑞)

資料庫連接資訊 jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mysql_demo jdbc.username=root jdbc.password=root

javabean Student.class

package entity; public class Student { private Integer id; private String name; private String sex; private Integer age; private Integer tId; public Integer getId { return id; } public void setId(Integer id) { this.id = id; } public String getName { return name; } public void setName(String name) { this.name = name; } public String getSex { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge { return age; } public void setAge(Integer age) { this.age = age; } public Integer gettId { return tId; } public void settId(Integer tId) { this.tId = tId; } }

mybatis配置 mybatis-cfg.xml

定義查詢介面StudentMapper.java

import java.util.List; /** * Created by zekai on 2017/6/10. */ public interface StudentMapper {//該介面只定義查詢方法 不執行具體查詢 //介面方法預設自帶public int insertStudent(Student student) throws Exception;// 插入 int判斷是否執行成功 Student selectOneById(int id) throws Exception;//查詢一條資料 List selectAllStudent;//查詢列表 封裝到list中 }

映射文件 StudentMapper.xml (必須與StudentMapper同名)

INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum)VALUES (#{id},#{name},#{sex},#{tId},#{age}) SELECT * FROM student WHERE Sid=#{id} SELECT *FROM student

測試方法(debug) Main.java

import dao.StudentMapper; import entity.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.List; //根據設定檔生成sqlsessionfactory /** * Created by zekai on 2017/6/10. */ public class Main { public static void main(String[] args) throws Exception { //io載入設定檔 InputStream in=Main.class.getResourceAsStream("resource/mybatis-cfg.xml"); //用構建器構建一個inputstream SqlSessionFactory factory=new SqlSessionFactoryBuilder.build(in); SqlSession session=factory.openSession; //取得mapper物件 調用mapper方法 StudentMapper mapper=session.getMapper(StudentMapper.class); Student student=new Student; // student.setId(20); // student.setAge(28); // student.setName("alowang"); // student.settId(2); // mapper.insertStudent(student); // student=mapper.selectOneById(2); List studentList=mapper.selectAllStudent; //記得提交 不提交等於啥都沒幹 session.commit; //關閉資源 session.close; } }
同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示