发布时间:2022-09-08 15:00
1.实现接口TypeHandler
2.继承BaseTypeHandler
表结构
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
`reg_time` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/**
*
* @ProjectName: springmvc-mybatis
* @Description: 自定义处理日期Hander,
* 将Date类型转换为时间戳字符串戳存入到数据库中
* 1.@MappedJdbcTypes定义的是JdbcType类型,这里的类型不可自己随意定义,
* 必须要是枚举类org.apache.ibatis.type.JdbcType所枚举的数据类型。
* 2.@MappedTypes定义的是JavaType的数据类型,描述了哪些Java类型可被拦截。
* 3.在我们启用了我们自定义的这个TypeHandler之后,数据的读写都会被这个类所过滤
*/
@MappedTypes({Date.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MyDateTypeHandler extends BaseTypeHandler<Date> {
/**
* 将时间戳字符串存入数据库
*/
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, String.valueOf(parameter.getTime()));
}
/**
* 把时间戳类型的字符串取出转换为Date
*/
@Override
public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
long timeLong = Long.parseLong(rs.getString(columnName));
Date date = new Date();
date.setTime(timeLong);
return date;
}
/**
* 把时间戳类型的字符串取出转换为Date
*/
@Override
public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
long timeLong = Long.parseLong(rs.getString(columnIndex));
Date date = new Date();
date.setTime(timeLong);
return date;
}
/**
* 把时间戳类型的字符串取出转换为Date
*/
@Override
public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
long timeLong = Long.parseLong(cs.getString(columnName));
Date date = new Date();
date.setTime(timeLong);
return date;
}
}
<resultMap id="resultListUser" type="User">
<id column="id" property="id" />
<result column="userName" property="userName" />
<result column="userAge" property="userAge" />
<result column="userAddress" property="userAddress" />
<result column="reg_time" property="regTime" javaType="java.util.Date" jdbcType="VARCHAR" typeHandler="com.wdzl.mybatis.type.MyDateTypeHandler"/>
resultMap>
<select id="findUserById" parameterType="int" resultMap="resultListUser">
select * from user where id = #{id}
select>
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="uid">
insert into user(userName,userAge,userAddress,reg_time) values(#{userName},#{userAge}, #{userAddress},
#{regTime,javaType=Date,jdbcType=VARCHAR,typeHandler=com.wdzl.mybatis.type.MyDateTypeHandler})
insert>
@Repository
public interface UserMapper {
public User findUserById(int uid);
public void insertUser(User user);
}
/** * 添加 */
public class TestAddUser {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void main(String[] args) {
insertUser();
}
public static void insertUser() {
User user = new User();
user.setUserName("spring");
user.setUserAge("101");
user.setUserAddress("hangzhou,xihu");
user.setRegTime(new Date());
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper userMapper = session.getMapper(UserMapper.class);
userMapper.addUser(user);
session.commit();
System.out.println("当前增加的用户 id为:" + user.getId());
} catch (Exception e) {
session.rollback();
}finally {
session.close();
}
}
}
package user;
import com.wdzl.mybatis.dao.UserMapper;
import com.wdzl.mybatis.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/**
*
* @ProjectName: springmvc-mybatis
* @Description: 查找
*/
public class TestGetUser {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void findUserById(int id){
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> users = userMapper.selectUserById2(id);
for(User u : users) {
System.out.println(u.getRegTime());
}
}
public static void main(String[] args) {
findUserById(3);
}
}
局部配置:
<resultMap id="resultListUser" type="User">
<id column="id" property="id" />
<result column="userName" property="userName" />
<result column="userAge" property="userAge" />
<result column="userAddress" property="userAddress" />
<result column="reg_time" property="regTime" javaType="java.util.Date" jdbcType="VARCHAR" typeHandler="com.wdzl.mybatis.type.MyDateTypeHandler"/>
resultMap>
<select id="findUserById" parameterType="int" resultMap="resultListUser">
select * from user where id = #{id}
select>
全局配置:
<typeHandlers>
<typeHandler handler="com.wdzl.mybatis.type.MyDateTypeHandler" />
typeHandlers>
商品表(items):
CREATE TABLE `items` (
`iid` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL COMMENT '商品名称',
`price` FLOAT(10,1) NOT NULL COMMENT '商品定价',
`detail` TEXT COMMENT '商品描述',
`pic` VARCHAR(64) DEFAULT NULL COMMENT '商品图片',
`createtime` DATETIME NOT NULL COMMENT '生产日期',
PRIMARY KEY (`iid`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
商品表插入数据:
INSERT INTO `items` VALUES (1, '台式机', '3000.0', '该电脑质量非常好!!!!', null, '2015-02-03 13:22:53');
INSERT INTO `items` VALUES (2, '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', null, '2015-02-09 13:22:57');
INSERT INTO `items` VALUES (3, '背包', '200.0', '名牌背包,容量大质量好!!!!', null, '2015-02-06 13:23:02');
用户表(user):
CREATE TABLE `user` (
`uid` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
用户表插入数据:
INSERT INTO `user` VALUES ('1','王五',NULL,'男',NULL);
INSERT INTO `user` VALUES ('10','张三','2014-07-10','女','北京市');
INSERT INTO `user` VALUES ('16','张小明',NULL,'男','河南郑州');
INSERT INTO `user` VALUES ('22','陈小明',NULL,'女','河南郑州');
INSERT INTO `user` VALUES ('24','张三丰',NULL,'男','河南郑州');
INSERT INTO `user` VALUES ('25','陈小明',NULL,'男','河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);
INSERT INTO `user` VALUES ('28', '赵四', '2017-05-03', '男', '辽宁');
INSERT INTO `user` VALUES ('29', '小灰灰', '2017-05-03', '女', '西安');
订单表(orders):
CREATE TABLE `orders` (
`oid` int(11) NOT NULL auto_increment,
`user_id` int(11) NOT NULL COMMENT '下单用户id',
`number` varchar(32) NOT NULL COMMENT '订单号',
`createtime` datetime NOT NULL COMMENT '创建订单时间',
`note` varchar(100) default NULL COMMENT '备注',
PRIMARY KEY (`oid`),
KEY `FK_order_1` (`user_id`),
CONSTRAINT `FK_order_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`uid`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
订单表插入数据:
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null);
订单明细表(orderdetail):
CREATE TABLE `orderdetail` (
`odid` int(11) NOT NULL auto_increment,
`order_id` int(11) NOT NULL COMMENT '订单id',
`items_id` int(11) NOT NULL COMMENT '商品id',
`items_num` int(11) default NULL COMMENT '商品购买数量',
PRIMARY KEY (`odid`),
KEY `FK_orderdetail_1` (`order_id`),
KEY `FK_orderdetail_2` (`items_id`),
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`oid`),
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`iid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
订单明细表插入数据:
INSERT INTO `orderdetail` VALUES ('1', '3', '1', '1');
INSERT INTO `orderdetail` VALUES ('2', '3', '2', '3');
INSERT INTO `orderdetail` VALUES ('3', '4', '3', '4');
INSERT INTO `orderdetail` VALUES ('4', '4', '2', '3');
1.sql语句
select orders.*,user.* from order, user where orders.user_id = user.uid
2.创建POJO(输出类型的包装类)
public class OrdersCustom extends Order {
// 下面添加用户属性
private String uname;
private String sex;
private String address;
// 省略 get 和 set 方法
}
3.UserMapper.xml:
<select id="findOrdersUser" resultType="OrdersCustom">
select orders.*,user.* from orders, user where orders.user_id = user.uid
select>
UserMapper接口:
// 查询订单, 关联查询用户信息
public List<OrdersCustom> findOrderUser() throws Exception;
<resultMap type="Order" id="OrderUserResultMap">
<!– column:表中的字段 property:javabean中字段 -->
<id column="oid" property="oid"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<association property="user" javaType="User">
<id column= "uid" property= "uid"/>
<result column="uname" property="uname"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
association>
resultMap>
resultType和resultMap
Intel RealSense Depth Camera D435i 跑通 RTAB-Map
大数据告诉你——垃圾围城,现行的垃圾分类制度,作用到底能有多大?
SAP S4 Material Management 库存模块 MARD 数据库表读取技术细节介绍
从底层结构开始学习FPGA----Xilinx 7 系列FPGA 的存储资源优势
Wallys/QCA9882/ WiFi 5 (802.11ac) mini PCIe higher Tx power
MindSpore报错“RuntimeError: Unexpected error. Inconsistent batch..