Mybatis示例

Mybatis配置文件

mybatis.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://127.0.0.1:3306/home_system"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mapping/LiuYanDao.xml"/>
        <mapper resource="com/mapping/UserDao.xml"/>
        <mapper resource="com/mapping/HuoWuBiaoDao.xml"/>
        <mapper resource="com/mapping/XiWangWuZiDao.xml"/>
        <!--。。。更多。。。。-->
    </mappers>
</configuration>

编写mapper.xml

UserDao.xml

<!--i引入dtd可以是下面的代码有提示-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.people_web.dao.IUserDao">
	<!--首先定义resultMap 作用是规定数据库字段与实体属性的关系-->
	<resultMap id="usersResultMap" type="com.people_web.domain.User">
		<!--
			id 标注主键字段
			column填写数据库字段名称
			property填写java属性名称
			jdbcType填写数据库字段类型(要使用大写而且字段类型是固定)
			javaType填写java实体属性名称
		-->
		<id column="user_id" property="userId" jdbcType="INTEGER" javaType="int"/>
		<!--非主键类型使用result-->
		<result column="user_name" property="userName" jdbcType="CHAR" javaType="String"></result>
		<result column="user_pwd" property="userPwd" jdbcType="CHAR" javaType="String"></result>
	</resultMap>
	<!--
		id属性要和Dao中的方法名称一致,
		mapper通过id寻找对应的Dao的方法
		如果返回的是基础数据类型 resultType 
		如果返回的是实体类型 resultMap
		也可以是parameterType 
		如果返回的是List resultMap+resultType(不加也可以)
	-->
	<!--登录,返回整型-->
	<select id="userLogin" resultType="int">
		select count(* from user_info where user_name=#{userName} and user_pwd=#{userPwd}
	</select>
	<!--根据id查一个,返回userResultMap对象-->
	<select id="findUserById" resultMap="userResultMap">
		select * from user_info where user_id=#{userId}
	</select>
	<!--查询所有,返回数组-->
	<select id="findAllUser" resultMap="userResultMap" resultType="java.util.ArrayList" >
		select * from user_info 
	</select>
	<!--模糊查询-->
	<select id="findUserByName" resultMap="userResultMap" resultType="java.util.ArrayList">
		select * from user_info where user_name like concat('%',#{userName},'%')
	</select>
	<!--增加语句-->
	<insert id="addUser" parameterType="com.people_web.domain.User">
        insert into user_info(msg,u_id,power) values (#{msg},#{u_id},#{power})
    </insert>
	<!--删除语句-->
    <delete id="delUser" parameterType="Integer">
        delete from user_info where id=#{id}
    </delete>
	<!--修改语句-->
    <update id="updateUser" parameterType="com.people_web.domain.User">
        update user_info set msg=#{msg} where id=#{id}
    </update>
</mapper>
Spring MVC 整合 MyBatis示例通常涉及以下几个步骤: 1. 添加依赖:在你的 Maven 或者 Gradle 项目中添加 Spring Web 和 MyBatis 的依赖。 ```xml <!-- Maven 示例 --> <dependency> <groupId>org.mybatis.spring</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.5.6</version> </dependency> <!-- Gradle 示例 --> implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.5.6' ``` 2. 配置数据源:Spring Boot 自带了对数据源的支持,如果使用 JPA,你需要配置 DataSource。对于 MyBatis,不需要额外的配置。 3. 创建 Mapper 接口:定义 SQL 查询操作的接口,并通过 `@Mapper` 注解标记。 ```java import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUser(int id); } ``` 4. 映射 XML 文件:编写 XML 映射文件,将 Mapper 接口的方法映射到具体的 SQL 语句。 ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <select id="getUser" resultType="com.example.demo.entity.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 5. 配置 SqlSessionFactory:在 Spring 容器启动时注入到应用中。 ```java @Configuration public class MyBatisConfig { @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { // 使用 MyBatis Builder API 或者 SqlSessionFactoryBuilder 构建工厂 SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); } } ``` 6. 创建 Service 类:注入 SqlSession 对象,利用它来执行 SQL 查询并处理结果。 ```java @Service public class UserService { private final SqlSessionFactory sqlSessionFactory; @Autowired public UserService(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public User getUser(int id) { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { return sqlSession.selectOne("UserMapper.getUser", id); } catch (Exception e) { throw new RuntimeException(e); } } } ``` 7. 在 Controller 中调用服务:创建 RESTful 控制器来访问 Service 并返回结果。 ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity<User> getUser(@PathVariable int id) { User user = userService.getUser(id); // 返回响应 } } ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值