2 oliver030 oliver030 于 2015.07.23 19:01 提问

刚学Hibernate,遇到数据插入不全的问题,求大神!

代码:
package com.java.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;

import com.java.bean.Student;

public class StudentTest {
private SessionFactory sessionFactory = null;
private Session session = null;
private Transaction transaction = null;
public void init() {
Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
public void destory(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void getAllPeople(){
init();
Student student = new Student(15,"Tomas",22,"男");
session.save(student);
destory();
}
}

package com.java.bean;

public class Student {
private int id;
private String name;
private int age;
private String sex;
public Student() {
}

public Student(int id, String name, int age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", sex=" + sex + "]";
}
}
结果id和name进去了,age和sex没有
图片说明
求大神!

8个回答

oliver030
oliver030   2015.07.23 19:24

问题已找到。我忘记在Student.hbm.xml里配置另外两个属性了。╮(╯▽╰)╭

zyb112211
zyb112211   2015.07.23 19:05

你是第一次添加就这样还是就这一次,第一次的话你看看是不是数据库字段不对头

oliver030
oliver030 第一次,前面是在mysql里插入的
2 年多之前 回复
Evankaka
Evankaka   Ds   Rxr 2015.07.23 19:13

这肯定是java类中的age;sex;和表中相应的字段没对应好

oliver030
oliver030 我java类里的age是int,sex是String,表里的age是int(2),sex是char(1),这样对吗?
2 年多之前 回复
u011313172
u011313172   2015.07.23 19:33

类的字段类型、数据库字段是否有,类型和类中皮不匹配,都没问题有可能是hibernate的映射文件中字段有没有类型对不对。

strutce
strutce   Ds   Rxr 2015.07.23 20:37

这样无懈可击,看看表映射文件或sql语句

troublemaker2014
troublemaker2014   2015.07.23 21:12

肯定是映射文件写错了,就是student.hbm.xml文件的属性和对象的映射建立的不对

zyb112211
zyb112211   2015.07.23 22:05

楼上逗比,楼主都已经说了问题所在了,你们还当没看见

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.07.23 22:23

下次你再配置的时候,最好先配置好表,然后一反射就OK了

Csdn user default icon
上传中...
上传图片
插入图片