我正在尝试使用 Hibernate 将 hashmap 的值写入数据库。
我的 POJO 类包 org.rahul;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
@Entity
@Table(name = "hash")
public class HashMapExample {
@Id
@GeneratedValue
private int id;
@ElementCollection
@MapKeyColumn(name = "key_key")
@JoinTable(name = "example_attributes", joinColumns =
@JoinColumn(name"example_id"))
private Map<String, String> map = new HashMap<String, String>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
主班
package org.rahul.hibernate;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.rahul.HashMapExample;
public class HashMapMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory sessionFactory = new AnnotationConfiguration()
.configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
String name = "Rahul";
String company = "Memoir";
Map<String, String> map = new HashMap<String, String>();
map.put(name, company);
Map<String, String> map1 = new HashMap<String, String>();
map1.put("XYZ", "ABC");
HashMapExample hash = new HashMapExample();
HashMapExample hash1 = new HashMapExample();
// hash.setId(2);
hash1.setMap(map);
hash.setMap(map1);
session.getTransaction();
session.save(hash);
session.save(hash1);
session.getTransaction().commit();
}
}
我希望获得包含键值对的列的表,但是我将键值作为不同的列。
example_attribut table description :
CREATE TABLE `example_attributes`
(
`example_id` INT(11) NOT NULL,
`map` VARCHAR(255) DEFAULT NULL,
`key_key` VARCHAR(255) NOT NULL,
PRIMARY KEY (`example_id`, `key_key`),
KEY `fkea50c74c5cd44e54` (`example_id`),
CONSTRAINT `fkea50c74c5cd44e54` FOREIGN KEY (`example_id`) REFERENCES
`hash` (`id`)
)
engine=innodb
DEFAULT charset=utf8
哈希表说明:
CREATE TABLE `hash` (
`id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
为什么我无法将字段 map 和 key_key 描述为 hashmap ?我希望它们像键值对一样位于单个字段中。谁能帮帮我吗 ?