IDEA中使用Mybatis的一个DEMO遇到的一些问题

本文介绍了在IntelliJ IDEA中使用MyBatis进行开发的步骤,包括创建Maven quickstart项目,配置MyBatis依赖,设置源代码和资源文件路径。详细讲解了使用XML配置文件和注解两种方式实现MyBatis映射,涉及主配置文件conf.xml,mapper.xml文件,接口定义,以及对象与数据库的映射。文中还提到了常见问题,如不添加默认构造函数导致的错误,并提供了测试类验证配置的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建项目:

使用maven创建的一个quickstart项目,然后在pom.xml中添加MyBatis的相关依赖,pom.xml文件如下:

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.0</version>
    </dependency>

    <!-- MySQL数据库依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>

  </dependencies>

然后观察下IDEA的项目结构:File -> Project Structure ->Modules

此时,代码的源路径为: src/main/java  资源文件的源路径为:src/main/java/resource

InputStream inputstream = class.getClassLoader().getResourceAsStream(resource)

在使用以上方法读取资源的时候,在IDEA中,如果resource不是设置的资源文件的源路径,那么读出的io流会报错,

为null,参见:getResourceAsStream的几种路径配置 。

以上为项目结构设置,下面简单介绍下使用 xml 文件 以及 注解方式的Mybatis使用方式。

2.使用xml配置映射文件方式

首先,我们看主配置文件conf.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">
            <transactionManager type="jdbc" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost/cloud_study" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="userMapper.xml" />
        <mapper resource="userOp.xml"/>
    </mappers>
</configuration>

需要注意的几个地方:

1. <transactionManager type="jdbc" /> 事务管理使用jdbc来完成

2. <dataSource> 标签中配置的是jdbc驱动,具体数据库,数据库连接用户名和密码

3.<mappers> 中注册了<mapper>映射文件。

然后,我们再来看一个具体的<mapper>文件:

这里一个mapper.xml文件与一个接口相对应,这里是对一个user表的操作来举例,user表里分别有id,name,corp(公司)属性。

Mybatis为一个ORM工具,即对象-关系映射模型,那么我们下面分别介绍下 对象User,以及将此对象与关系数据库映射的文件 UserOp.interface 与 UserOp.xml 。

1. User 类

public class user {
    private int id;
    private String name;
    private String corp;

    public user(){} 

    public user(int id, String name, String corp) {
        this.id = id;
        this.name = name;
        this.corp = corp;
    }

    public user(String name, String corp) {
        this.name = name;
        this.corp = corp;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCorp() {
        return corp;
    }

    public void setCorp(String corp) {
        this.corp = corp;
    }
}

需要注意的是,如果不加默认的构造函数,会报错:

org.apache.ibatis.executor.ExecutorException: No constructor found in com....

所以需要加一个默认的构造函数。

2. UserOp.interface

public interface UserOP {

    public void addUser(user user);

    public void updateUser(user user);

    public void deleteUser(int id);

    public user getUser(int id);

}

此接口中定义了几种操作,在使用时,调用此接口中的方法。

3.UserOp.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.netease.UserOP">
    <insert id="addUser" parameterType="com.netease.user"
    useGeneratedKeys="true" keyProperty="id">
      insert into user (name,corp) values (#{name}, #{corp})
    </insert>

    <select id="getUser" parameterType="int"
            resultType="com.netease.user">
        select id ,name,corp from user where id =#{id}
    </select>
    
    <update id="updateUser" parameterType="com.netease.user">
        update user set name = #{name}, corp = #{corp} where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="com.netease.user">
        delete from user where id = #{id}
    </delete>
</mapper>

需要注意的几点:

<mapper>的namespace属性,对应相关的接口;

<select>标签中的id,对应指定接口中的方法, parameterType为传入的参数类型,resultType为返回的参数类型。

id = #{id},其中 前面的id为数据库的属性,第二个为对象的属性。

4. 测试类

public class test_main_op {
    public static void main(String[] args) {
        String resource = "conf.xml";
        InputStream is = test_main.class.getClassLoader().getResourceAsStream(resource);
        // 创建SqlSessonFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //获取Session
        SqlSession session = sessionFactory.openSession(true);

        try {
            //获取操作类
            UserOP userOP = session.getMapper(UserOP.class);
            user user1 = new user("wade","nba");
            //完成操作
            userOP.addUser(user1);

            user1.setCorp("lining");
            userOP.updateUser(user1);

        } finally {
            //关闭Session
            session.close();
        }
    }
}

至此,一个简单的MyBatis使用Demo就完成了,下面看看如何使用注解的方式来进行sql查询。

3.使用注解的方式

1. GetUserInfoAnnotation.interface

public interface GetUserInfoAnnotation {

    @Select("select * from user where id = #{id}")
    public user getUser(int id);
}

2.测试类

public class test_main_anotation {
    public static void main(String[] args) {
        String resource = "conf.xml";
        InputStream is = test_main.class.getClassLoader().getResourceAsStream(resource);

        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                .build(is);
        // 增加配置
        Configuration conf = sessionFactory.getConfiguration();
        conf.addMapper(GetUserInfoAnnotation.class);

        SqlSession session = sessionFactory.openSession();

        try {
            GetUserInfoAnnotation getUserInfo = session.getMapper(GetUserInfoAnnotation.class);
            user user1 = getUserInfo.getUser(1);
            System.out.println(user1.getId() + " " + user1.getName() + " " + user1.getCorp());
        } finally {
            session.close();
        }
    }
}

 

### 测量线段或路径长度的方法 在 Altium Designer 中,可以通过内置工具来精确测量 PCB 上的线段或路径长度。以下是具体方法: 1. **启动测量命令** 用户可以使用 `Measure Distance` 功能来进行距离测量。通过点击菜单栏中的 `Tools -> Measure -> Measure Distance` 来激活该功能[^1]。 2. **选择起点与终点** 激活测量工具后,在工作区中单击鼠标左键定义起始点,随后移动光标到目标位置并再次单击以设置结束点。此时屏幕上会显示两点之间的直线距离以及 X 和 Y 方向上的分量距离[^2]。 3. **路径长度测量** 如果需要测量多段线路总长,则可依次拾取每一段轨迹端点直至完成整个路径选取。每次新增选定点时,软件都会累加前一节点至当前节点间的距离值,并最终给出整体累计数值作为路径全长的结果展示给用户查看。 4. **单位切换** 默认情况下,测量结果显示为毫米 (mm),如果希望更改默认度量衡制式比如英寸(inch)等其他形式的话,可以在 preferences 设置里调整全局工程参数配置项下的 Units 部分相应选项即可实现不同计量体系间自由转换操作。 ```python # 示例 Python 脚本用于自动化批量读取多个对象的距离(仅作演示用途) import altium_api as api def measure_objects(object_list): total_length = 0 for obj in object_list: start_point, end_point = get_object_endpoints(obj) length = calculate_distance(start_point, end_point) total_length += length return total_length def calculate_distance(point_a, point_b): dx = point_b['x'] - point_a['x'] dy = point_b['y'] - point_a['y'] distance = (dx**2 + dy**2)**0.5 return distance objects_to_measure = [...] # 假设这是要测量的对象列表 total_len = measure_objects(objects_to_measure) print(f"Total Length of Objects: {total_len} mm") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值