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"; }