Java web开发中,把hstore类型数据插入PostgreSQL数据库中

1.首先建立数据库表hstore_tb

CREATE EXTENSION hstore; 
create table hstore_tb(
key_value hstore
);

2.HstoreMapper.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.op.component.serverInfo.mapper.HstoreMapper">
 	
 	<insert id="insertHstore" parameterType="String" >
 		insert into hstore_tb(key_value) values(#{key_value}::hstore);
 		
 	</insert>
 </mapper>

3.HstoreMapper.java

import com.op.util.mapper.CommonMapper;

public interface HstoreMapper extends CommonMapper{
	public int insertHstore(String key_value);
}

4.服务实现HstoreImpl.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.op.component.serverInfo.mapper.HstoreMapper;

@Service("hstore_service")
public class HstoreImpl {
	@Autowired
	public HstoreMapper hsMapper;
	
	public boolean addHstore(String key_value){
		int res= hsMapper.insertHstore(key_value);
		if(res>0) return true;
		return false;
	}
}

5.mybatis配置文件中可能需要加上这个代码,不过看个人的项目配置情况而定

 <configuration> 
    <mappers>
    	
    	<mapper resource="com/op/component/serverInfo/mapper/HstoreMappper.xml"/>
    	
    </mappers>
</configuration>

6.TestController.Java

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.op.component.serverInfo.service.HstoreImpl;
import com.op.component.serverInfo.service.ServerInfoServiceImpl;
import com.op.model.ServerInfo;

@Controller
@RequestMapping("/test")
public class TestController {
        @Autowired
	public HstoreImpl hsService;
	
        @RequestMapping(method=RequestMethod.GET,value="/addhs")
	public ModelAndView addHstore(){
		String key_value="name=>hello";
		boolean res = hsService.addHstore(key_value);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("result", res);
		ModelAndView mav = new ModelAndView("result", map);
		return mav;
	}
}

整个程序,关键地方是加上”::hstore

insert into hstore_tb(key_value) values(#{key_value}::hstore);

说明:本文是因为社区上有人问,所以查找资料写出来的,写的比较简单,毕竟是一个测试案例只是为了说明如何做,才能让Java中,实现插入hstore类型数据。写的不好的地方欢迎在下方评论,谢谢~~(最后,本文是个人原创,转载请注明出处!!!

你可能感兴趣的:(java,postgre,hstore)