首先建立一个maven 项目,并导入相应的jar包
然后自己创建一个数据库表:
写一个接口IUserMapper:
再写一个实体类,get set方法,构造方法,并重写toString 方法:(后面的省略了)
这时候写配置文件xml:
User.xml:
<mapper namespace="mybatis.IUserMapper">
<resultMap type="mybatis.User" id="1">
<result property="id" column="id" />
<result property="name" column="name"/>
<result property="dept" column="dept"/>
<result property="phone" column="phone"/>
<result property="website" column="website"/>
</resultMap>
<select id="GetUserByID" parameterType="int" resultMap="1">
select * from `user` where id = #{id}
</select>
<insert id="insertUser" parameterType="mybatis.User" >
INSERT INTO USER (name,
dept, website,phone)
VALUES(#{name}, #{dept}, #{website}, #{phone})
</insert>
其中 property对应实体类里定义的字段,column对应数据库中的字段,<select>中 id 对应接口中定义的方法,parameterType对应返回类型,resultMap值对应上面<resultMap>的id值,
然后配置Configure.xml:
<!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" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/User.xml" />
</mappers>
</configuration>
最后写个测试类:
运行以后看数据库:
完成~