SpringBoot项目问题总结
一. MyBatis获取刚插入实体的id
1.在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是表格的字段名。
<insert id="insert" parameterType="Spares"
useGeneratedKeys="true" keyProperty="id">
insert into system(name) values(#{name})
</insert>
2.Mybatis执行完插入语句后,自动将自增长值赋值给对象systemBean的属性id。因此,可通过systemBean对应的getter方法获取!
int count = systemService.insert(systemBean);
int id = systemBean.getId(); //获取到的即为新插入记录的ID
【注意事项】
1.Mybatis Mapper 文件中,“useGeneratedKeys”和“keyProperty”必须添加,而且keyProperty一定得和java对象的属性名称一直,而不是表格的字段名
2.java Dao中的Insert方法,传递的参数必须为java对象,也就是Bean,而不能是某个参数。
二. MyBatis自增id
插入一条实体时,id可以不必传入,一般会自动递增,但是有次没有自动递增,还报了下面的错:
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed; nested exception is
org.mybatis.spring.MyBatisSystemException: nested exception is
org.apache.ibatis.reflection.ReflectionException: Could not set
property ‘id’ of ‘class
com.ziroom.qa.telot.tool.entity.CodeBlockEntity’ with value
‘1229320084688879618’ Cause: java.lang.IllegalArgumentException:
argument type mismatch] with root cause
java.lang.IllegalArgumentException: argument type mismatch
查看数据库,id已经选择了自动递增。
查看实体类,是这样写的:
查看Dao层,是这样写的:
经过实验发现如果Dao层extends了BaseMapper,Entity的 Integer id必须加个注释,设置为自动递增,否则不会自动递增:
实验还发现,如果id的类型设置为int时,可以不用加注释,即可递增。
总结一下,如果Dao层 extends BaseMapper,id必须写为:
@TableId(type = IdType.AUTO)
private Integer id;
或者
private int id;
三. 文件创建并写入
1.File创建空文件
filePath = "D:\\tmp\\1.txt"
File file = new File(filePath);
file.createNewFile(); //创建文件
file.mkdirs(); //如果filePath是文件夹,用这个创建文件夹
2.File创建的是空文件,可以通过FileWritter写入。FileWritter支持int、byte、char、String类型的写入。
try {
File file = new File(filePath);
//filePath所在的文件夹必须存在
file.getParentFile().mkdirs(); //先确保文件夹存在
FileWriter fileWriter = new FileWriter(filePath); //这里也会创建文件
fileWriter.write("lalalala");
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
3.通过流创建文件
FileOutputStream fis = new FileOutputStream(filePath); //这句话会创建文件
OutputStreamWriter out = new OutputStreamWriter(fis,"UTF-8");
out.write("lalalala");
out.flush();
out.close();
fis.close();
四. Java对象与JSON对象的互转
1.Java对象转JSON对象
Student stu = new Student();
//Java对象转化为JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
2.Java对象转JOSN字符串
String stuString= JSONObject.toJSONString(stu);
3.JSON对象转JSON字符串
String stuString= jsonObject.toJSONString();
4.JSON字符串转JSON对象
JSONObject jsonObject = JSONObject.parseObject(stuString);
5.JSON对象转Java对象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
6.JSON字符串按顺序解析成Map对象
由于Map是无序的,所以如果直接解析成Map将会乱序,所以我们要利用LinkMap。
Map<Integer, Object> map = (Map)JSONObject.parseObject(str, LinkedHashMap.class, Feature.OrderedField);