<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://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
configuration>
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//获取session
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
User user = sqlSession.selectOne("test.findUserById", 10);
System.out.println(user);
<mapper namespace="test">
<select id="findUserById" parameterType="Integer" resultType="User">
select * from user where id = #{v}
select>
mapper>
#{}:在mybatis数据库语句中表示占位符,占位符有个特点就是自动加上’'单引号。
${}:在mybatis数据库语句中是拼接的意思,没有加上单引号。
<select id="findUserByUsername" parameterType="String" resultType="com.it.mybatis.pojo.User">
select * from user where username like "%"#{haha}"%"
select>
//执行Sql语句
User user = new User();
user.setUsername("何炅");
user.setBirthday(new Date());
user.setAddress("sadfsafsafs");
user.setSex("男");
int i = sqlSession.insert("test.insertUser", user);
sqlSession.commit();
<insert id="insertUser" parameterType="com.it.mybatis.pojo.User">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
select LAST_INSERT_ID()
selectKey>
insert into user (username,birthday,address,sex)
values (#{username},#{birthday},#{address},#{sex})
insert>
<update id="updateUserById" parameterType="com.it.mybatis.pojo.User">
update user
set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address} where id = #{id}
update>
<delete id="deleteUserById" parameterType="Integer">
delete from user where id = #{vvvvv}
delete>
public User findUserById(Integer id);
<mapper namespace="com.it.mybatis.mapper.UserMapper">
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSEssion帮我生成一个实现类 (给接口)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findUserById(10);
System.out.println(user);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
<typeAliases>
<package name="com.itheima.mybatis.pojo"/>
typeAliases>