Mybatis入門

1.導入jar包

2.創建與數據庫表對應的實體類

package cn.zzu.entity;

public class Student {
	private Integer id;
	private String name;
	private Integer age;
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
}

2.在src下創建conf.xml文件,並配置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>
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事務管理 -->
			<transactionManager type="JDBC"></transactionManager>
			<!-- 使用數據庫連接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql:///mybatis?characterEncoding=utf-8"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
	<!-- 引入Mapper1.xml文件 -->
	<mappers>
		<mapper resource="SalMap/Mapper1.xml"/>
	</mappers>
</configuration>

3.創建mapper.xml並配置

<?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">
<!-- namespace命名空間
	用來隔離sql
 -->
 <mapper namespace="student">
 	<!-- 通過id來查詢一個用戶 
 		id屬性:sql的名稱,namespace+id用來定位具體的sql(標識)
 		parameterType屬性:參數類型
 		resultType屬性:返回值
 		如果bean與數據庫一一對應,則會自動映射   where id=#{v},#{} 佔位符,裏面要寫一個任意字符
 	-->
 	<select id="findStudentById" parameterType="Integer" resultType="cn.zzu.entity.Student">
 		select * from student where id=#{v}
 	</select>
 </mapper>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章