通过MyBatis操作数据库

简单配置

  • mybatis.mapper-locations = classpath*:mapper/**/*.xml
    设置所有的classpath里面的mapper目录下所有的xml文件都是我的mybatis.mapper的映射文件

  • mybatis.type-aliases-package = 类型别名的包名
    通过去指定我的类型别名的使用的包前缀,来把我的package写在配置项里面,我在映射时,只需要写类名。

  • mybatis.type-handlers-package = TypeHandler扫描包名
    是我们mybatis做一个类型转换时,用的辅助类,可以去指定TypeHandler包的一个前缀

  • mybatis.configuration.map-underscore-to-camel-case = true
    把我们下划线转换为驼峰规则

Mapper 的定义与扫描

  • @MapperScan 配置扫描位置
    扫描mapper映射,
  • @Mapper 定义接口
    所有 Mapper 的接口上面,都要加@Mapper注解
  • 映射的定义—— XML 与注解

@Results的基本用法。当数据库字段名与实体类对应的属性名不一致时,可以使用@Results映射来将其对应起来。column为数据库字段名,porperty为实体类属性名,jdbcType为数据库字段数据类型,id为是否为主键。
@Data注解在类上时,简化java代码编写,为该类提供读写属性,还提供了equals(),hashCode(),toString()方法


@Mapper   //标明是一个Mapper接口,需要被扫描
public interface CoffeeMapper {
    @Insert("insert into t_coffee (name, price, create_time, update_time)"
            + "values (#{name}, #{price}, now(), now())")
    @Options(useGeneratedKeys = true)  ////说明我要使用生成的keys, 会进行回填
    int save(Coffee coffee);  //返回受更新的结果条数

    @Select("select * from t_coffee where id = #{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"), //@Results的基本用法。当数据库字段名与实体类对应的属性名不一致时,可以使用@Results映射来将其对应起来。column为数据库字段名,porperty为实体类属性名,jdbcType为数据库字段数据类型,id为是否为主键。
            @Result(column = "create_time", property = "createTime"),  //create_time做了一个下划线到驼峰的映射
            // map-underscore-to-camel-case = true 可以实现一样的效果
            // @Result(column = "update_time", property = "updateTime"),
    })
    Coffee findById(@Param("id") Long id);  //@Param指定我们传入的是一个id
}






@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {
    private Long id;
    private String name;
    private Money price;
    private Date createTime;
    private Date updateTime;
}


package geektime.spring.data.mybatisdemo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 在 Money 与 Long 之间转换的 TypeHandler,处理 CNY 人民币
 */
public class MoneyTypeHandler extends BaseTypeHandler<Money> {
    @Override  //设置的时候需要做的操作
    public void setNonNullParameter(PreparedStatement ps, int i, Money parameter, JdbcType jdbcType) throws SQLException {
        ps.setLong(i, parameter.getAmountMinorLong());
    }

    @Override//取值的时候需要做的操作
    public Money getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseMoney(rs.getLong(columnName));
    }

    @Override
    public Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseMoney(rs.getLong(columnIndex));
    }

    @Override
    public Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseMoney(cs.getLong(columnIndex));
    }

    private Money parseMoney(Long value) {
        return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
    }
}




@SpringBootApplication
@Slf4j
@MapperScan("geektime.spring.data.mybatisdemo.mapper")
public class MybatisDemoApplication implements ApplicationRunner {
	@Autowired
	private CoffeeMapper coffeeMapper;

	public static void main(String[] args) {
		SpringApplication.run(MybatisDemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		Coffee c = Coffee.builder().name("espresso")
				.price(Money.of(CurrencyUnit.of("CNY"), 20.0)).build();
		int count = coffeeMapper.save(c);
		log.info("Save {} Coffee: {}", count, c);

        Coffee b = Coffee.builder().name("latte")
				.price(Money.of(CurrencyUnit.of("CNY"), 25.0)).build();
		count = coffeeMapper.save(b);
		log.info("Save {} Coffee: {}", count, b);

        Coffee	a = coffeeMapper.findById(c.getId());
		log.info("Find Coffee: {}", a);
	}
}


注:因为有  @Options(useGeneratedKeys = true) ,所以id会自动回填。



发布了59 篇原创文章 · 获赞 6 · 访问量 984

猜你喜欢

转载自blog.csdn.net/weixin_43790623/article/details/103000026