javaeye 阅读(75) 评论(0)

1.POM里添加依赖

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.4</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.11</version>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.12</version>
	<scope>provided</scope>
</dependency>

在<build></build>里面添加:

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>


否则,包里面的xml文件无法读取,会显示错误:Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/huawei/testdemo/repository/UserRepository.xml


2.数据库里添加数据表
CREATE TABLE `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8 NOT NULL,
`age` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB

 

3.实体类(依赖lombok)
创建类com.huawei.testdemo.entity.User

import lombok.Data;

@Data
public class User {
    private long id;
    private String username;
    private int age;
}

 

4.创建MyBatis配置文件config.xml 配置MyBatis运行环境

配置JDBC事务管理(类型为JDBC):
<transactionManager type="JDBC"></transactionManager>

 

配置JDBC数据源连接池(类型为POOLED):

<dataSource type="POOLED">
    <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
</dataSource>

5.持久层接口
5.1 使用原生接口(不推荐,略)
自定义SQL语句,写在Mapper.xml文件里。
为每个实体类创建对应的Mapper.xml,例如UserMapper.xml
在config.xml里注册该例如UserMapper.xml

5.2 代理接口
创建类repository.UserRepository

public interface UserRepository {
    public int save(User user);
    public int update(User user);
    public int deleteById(long id);
    public List<User> findAll();
    public List<User> findByUser();
}

mapper映射文件UserRepository.xml

<insert id="save" parameterType="com.huawei.testdemo.entity.User">
    insert into users(username,age) values(#{username},#{age})
</insert>
<update id="update" parameterType="com.huawei.testdemo.entity.User">
    update users
    <set>
        <if test="username!=null">
            username = #{username},
        </if>
        <if test="age!=0">
            age = #{age}
        </if>
    </set>
    where id = #{id}
</update>

<delete id="deleteById" parameterType="long">
    delete from users where id = #{id}
</delete>
<select id="findAll" resultType="com.huawei.testdemo.entity.User">
    select * from users
</select>
<select id="findByUser" parameterType="com.huawei.testdemo.entity.User" resultType="com.huawei.testdemo.entity.User">
select * from users
<where>
    <choose>
        <when test="id!=0">
            id = #{id}
        </when>
        <when test="username!=null">
            and username = #{username}
        </when>
        <when test="age!=0">
            and age = #{age}
        </when>
    </choose>
</where>
</select>

-------------------
6.代码

InputStream inputStream = ResolverUtil.Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.huawei.testdemo.repository.UserRepository.save";
User user = new User("小陈", 23);
sqlSession.insert(statement, user);
sqlSession.commit();
sqlSession.close();

--------------------------
错误信息:
Error updating database. Cause: java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
### The error may exist in com/huawei/testdemo/repository/UserRepository.xml

 

解决方案:
1)修改数据库变量
mysql> set global time_zone='+8:00';

2)连接MySQL时,指定时区为UTC
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property>
--------------------------

学习视频:https://www.bilibili.com/video/BV1V7411w7VW


发表评论
切换编辑模式