mybatis是一個持久層框架,支持SQL查詢,存儲過程等,配置靈活,使用方便。經過使用XML配置很好的和JDBC結合,很方便的操做數據庫java
首先經過maven引入mybatis的第三方組件mysql
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
CREATE TABLE 'Student' ( 'Id' int(11) NOT NULL AUTO_INCREMENT, 'Name' varchar(50) DEFAULT NULL, 'Code' varchar(50) DEFAULT NULL, PRIMARY KEY ('Id') ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf-8
package dto; public class Student{ private int Id ; public int getId() { return Id; } public void setId(int id) { Id = id; } private String Code; public String getCode() { return Code; } public void setCode(String Code) { Code = Code; } private String Name ; public String getName() { return Name; } public void setName(String Name) { Name = Name; } }
<?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="mapping.Studentmapper"> <!-- 指定查詢SQL, parameterType是傳入參數類型,resultType是返回結果--> <select id="getStudent" parameterType="int" resultType="dto.Student"> SELECT * FROM Student WHERE id=#{id} </select> </mapper>
int i=1;String s="s123";spring
id=#i# and name=#{s} ----> id=1 and name='s123' //使用#會在字符串類型外面自動加上單引號''sql
id=$i$ and name=${s} ----> id=1 and name=s123 //使用$時,直接替換內容,不做其餘處理數據庫
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置數據庫鏈接信息 url中的erp爲數據名稱--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/erp" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!-- 指定映射文件 --> <mapper resource="mapping/skusMapper.xml"/> </mappers> </configuration>
@Controller @RequestMapping("/Home") public class HomeController { @Resource(name="applePhone") private IMobilePhone phone; @RequestMapping(value="index") public String Index() { String msg=phone.PhoneBrand(); System.out.print(msg); String resource = "/conf.xml"; //加載mybatis的配置文件 InputStream inputstream =this.getClass().getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputstream); SqlSession session = sessionFactory.openSession(); String statesql= "mapping.Studentmapper.getStudent"; //在StudentMapper.xml中有命名空間+方法名 Student student = session.selectOne(statesql, 1); System.out.println(student.getName()); return "index"; }