简单的mybatis项目构建
使用maven构建项目:
依赖包:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
mybatis配置文件:mybatis-config.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>
<typeAliases>
<typeAlias alias="User" type="com.qfedu.mybatis.entity.User" />
</typeAliases>
<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://localhost:3306/dang?useUnicode=true&CharacterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/qfedu/mybatis/dao/UserDao.xml" />
</mappers>
</configuration>
现在的Dao层直接用XML文件实现,比如:UserDao.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">
<mapper namespace="com.qfedu.mybatis.dao.UserDao">
<resultMap type="User" id="foo">
<id property="username" column="username" />
<result property="password" column="password" />
<result property="nickname" column="nickname" />
<result property="email" column="email" />
<result property="gender" column="gender" />
<result property="photo" column="photo" />
</resultMap>
<select id="findAll" resultMap="foo">
select * from tb_user
</select>
<select id="findById" parameterType="String" resultType="User">
select * from tb_user where username = #{username}
</select>
<insert id="save" parameterType="User">
insert into tb_user values (default,#{username},#{password},#{nickname},#{email},#{gender},#{photo})
</insert>
<delete id="delete" parameterType="String">
delete from tb_user where username = #{username}
</delete>
<update id="update" parameterType="User">
update tb_user set email=#{email} where username = #{username}
</update>
</mapper>
简单连接数据库实验:
package com.qfedu.mybatis;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.qfedu.mybatis.dao.UserDao;
import com.qfedu.mybatis.entity.User;
public class App {
public static void main(String[] args) throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory =
new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
User user = userDao.findById("jjjj");
user.setEmail("834582272@qq.com");
userDao.update(user);
// userDao.delete("hellokitty");
session.commit();
session.close();
}
}