при обновление таблицы получаю ошибку 'student_id' doesn't have a default value'

141
17 марта 2019, 19:00

Пишу программу которая показывает какие дополнительные уроки посещает ученик, вот сущности

    @Entity
    @Table(name = "student")
    @NamedQueries({
            @NamedQuery(name = "Student.findAll", query = "select c from Student 
    c"),
            @NamedQuery(name = "Student.findById",
                    query = "select distinct c from Student c left join fetch 
    c.group t left join fetch c.lesson h where c.studentID = :id"),
            @NamedQuery(name = "Student.findAllWithDetalis",
                    query = "select distinct c from Student c left join fetch 
     c.group t left join fetch c.lesson h")
    })
     public class Student implements Serializable {
        private Long studentID;
        private String firstname;
        private String surname;
        private String patronymic;
        private  Set<Lesson> lesson = new HashSet<>();
        private Group group;
        private Set<Subject> subjects = new HashSet<>();
        private Set<Attendance> attendances = new HashSet<>();
        public Student() {}
        public Student(String surname,String firstname, String patronymic) {
            this.firstname = firstname;
            this.surname = surname;
            this.patronymic = patronymic;
        }
        @Id
        @GeneratedValue(strategy = IDENTITY)
        @Column(name = "student_id")
        public Long getStudentID() {
            return studentID;
        }
        public void setStudentID(Long studentID) {
            this.studentID = studentID;
        }
        @Column(name = "firstname")
        public String getFirstname() {
            return firstname;
        }
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }
        @Column(name = "surname")
        public String getSurname() {
            return surname;
        }
        public void setSurname(String surname) {
            this.surname = surname;
        }
        @Column(name = "patronymic")
        public String getPatronymic() {
            return patronymic;
        }
        public void setPatronymic(String patronymic) {
            this.patronymic = patronymic;
        }
        @ManyToMany
        @JoinTable(name = "student_to_lesson",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "lesson_id"))
        public Set<Lesson> getLesson() {
            return lesson;
        }
        public void setLesson(Set<Lesson> lesson) {
            this.lesson = lesson;
        }
        @OneToMany
        @JoinTable(name = "student_to_attend", joinColumns = @JoinColumn(name = 
        "attend_id"))
        public Set<Attendance> getAttendances() {
            return attendances;
        }
        public void setAttendances(Set<Attendance> attendances) {
            this.attendances = attendances;
        }
        public void addAttendances(Attendance attendance){
            attendance.setStudent(this);
            getAttendances().add(attendance);
        }
        public void removeAttedances(Attendance attendance){
            getAttendances().remove(attendance);
        }
        @ManyToOne()
        @JoinTable(name = "student_to_group", joinColumns = @JoinColumn(name = 
        "group_id"))
        public Group getGroup() {
            return group;
        }
        public void setGroup(Group group) {
            this.group = group;
        }
       @OneToMany(fetch = FetchType.EAGER)
       @JoinTable(name = "student_to_subject",joinColumns = @JoinColumn(name = 
       "subject_id"))
        public Set<Subject> getSubjects() {
            return subjects;
        }
        public void setSubjects(Set<Subject> subjects) {
            this.subjects = subjects;
        }
        public void addSubject(Subject subject){
            getSubjects().add(subject);
        }
        public void removeSubject(Subject subject){
            getSubjects().remove(subject);
        }
      }
     @Entity
     @Table(name = "group_")
     @NamedQuery(name = "Group.findByName",
            query = "select distinct c from Group c  where c.nameGroup = :name")
     public class Group implements Serializable {
        private Long groupId;
        private String nameGroup;
        private Set<Student> students = new HashSet<>();
        public Group() {
        }
        public Group(String nameGroup) {
            this.nameGroup = nameGroup;
        }
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "group_id")
        public Long getGroupId() {
            return groupId;
        }
        public void setGroupId(Long groupId) {
            this.groupId = groupId;
        }
        @Column(name = "name_group")
        public String getNameGroup() {
            return nameGroup;
        }
        public void setNameGroup(String nameGroup) {
            this.nameGroup = nameGroup;
        }
        @OneToMany
        @JoinTable(name = "student_to_group",joinColumns = @JoinColumn(name = 
       "student_id"))
        public Set<Student> getStudents() {
            return students;
        }
        public void setStudents(Set<Student> students) {
            this.students = students;
        }
        public void addStudent(Student student){
            student.setGroup(this);
            getStudents().add(student);
        }
        public void removeStudent(Student student){
            getStudents().remove(student);
        }
       }
      @Entity
      @Table(name = "subject")
      @NamedQuery(name = "Subject.findByName",
            query = "select distinct c from Subject c  where c.subjectName = 
     :name")
     public class Subject implements Serializable {
        private Long subjectId;
        private String subjectName;
        private Set<Teacher> teacher = new HashSet<>();
        private Lesson lesson;

        public Subject() {
        }
        public Subject(String subjectName) {
            this.subjectName = subjectName;
        }
        @Id
        @Column(name = "subject_id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        public Long getSubjectId() {
            return subjectId;
        }
        public void setSubjectId(Long subjectId) {
            this.subjectId = subjectId;
        }

        @Column(name = "subject_name")
        public String getSubjectName() {
            return subjectName;
        }
        public void setSubjectName(String subjectName) {
            this.subjectName = subjectName;
        }
        @OneToMany
        @JoinTable(name = "teacher_to_subject", joinColumns = @JoinColumn(name = 
       "teacher_id"))
        public Set<Teacher> getTeacher() {  return teacher;
        }
        public void setTeacher(Set<Teacher> teacher) {
            this.teacher = teacher;
        }
        public void addTeacher(Teacher teacher){
           teacher.setSubject(this);
            getTeacher().add(teacher);
        }
        public void removeteacher(Teacher teacher){
            getTeacher().remove(teacher);
        }
      }
     <?xml version="1.0" encoding="UTF-8"?>
     <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/school_journal?useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" autowire="byType">
        <property name="entityManagerFactory" ref="emf"/>
    </bean>
    <tx:annotation-driven proxy-target-class="true"/>
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="kz.nis"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQL8Dialect</prop>
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.jdbc.fetch_size">50</prop>
                <prop key="hibernate.jdbc.batch_size">10</prop>
                <prop key = "hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <context:annotation-config />
    <context:component-scan base-package="kz.nis"/>
</beans>
таблица в БД MySQL
create table  student(
  student_id bigint not null primary key auto_increment
  ,firstname varchar(60) not null
  ,surname varchar (60) not null
  ,patronymic varchar (60) not null
  );
create table  group_ (
  group_id bigint not null primary key auto_increment
  ,name_group varchar(60)not null
);
create table  subject(
   subject_id bigint not null primary key auto_increment
  , subject_name varchar (60) not null
);
create table student_to_group(
  student_id bigint not null
  , group_id bigint not null
  , primary key(student_id, group_id)
  , constraint fk_student_to_group_1 foreign key(student_id)
  references student(student_id)
   , constraint fk_student_to_group_2 foreign key(group_id)
    references group_(group_id)
);
create table student_to_subject(
  student_id bigint not null
  ,subject_id bigint not null
  ,primary key(student_id, subjectt_id)
  ,constraint fk_student_to_subject_1 foreign key(student_id)
    references student(student_id)
  , constraint fk_student_to_subject_2 foreign key(subject_id)
    references subject(subject_id)
);
при выполнение кода
public class Main {
    public static void main(String[] args) {
        GenericXmlApplicationContext context = new GenericXmlApplicationContext();
        context.load("classpath:META-INF/app-context-annotation.xml");
        context.refresh();
        StudentDAO studentDAO = context.getBean("jpaStudentDAO", StudentDAOImpl.class);
        GroupDAO groupDAO = context.getBean("jpaGroupDAO",GroupDAOImpl.class);
        SubjectDAO subjectDAO = context.getBean("jpaSubjectDAO", SubjectDAOImpl.class);
        LessonDAO lessonDAO  = context.getBean("jpaLessonDAO", LessonDAOImpl.class);
        TeacherDAO teacherDAO = context.getBean("jpaTeacherDAO", TeacherDAOImpl.class);

        Student student = studentDAO.findById(1);
        Group group =  groupDAO.findByName("11");
        student.setGroup(group);
        //student.addSubject(subjectDAO.findByName("Physics"));
        studentDAO.save(student);
}
} получаю ошибку
INFO: Student saved with id 1
Hibernate: insert into student_to_group (group_group_id, group_id) values (?, ?)
Oct 29, 2018 7:15:48 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Oct 29, 2018 7:15:48 PM org.hibernate.engine.jdbc.batch.internal.BatchingBatch performExecution
ERROR: HHH000315: Exception executing batch [java.sql.BatchUpdateException: Field 'student_id' doesn't have a default value], SQL: insert into student_to_group (group_group_id, group_id) values (?, ?)
Oct 29, 2018 7:15:48 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1364, SQLState: HY000
Oct 29, 2018 7:15:48 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Field 'student_id' doesn't have a default value
Oct 29, 2018 7:15:48 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.GenericJDBCException: could not execute batch]
Exception in thread "main" org.springframework.orm.jpa.JpaSystemException: could not execute batch; nested exception is org.hibernate.exception.GenericJDBCException: could not execute batch
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671)
    at kz.nis.data.dao.studentDAO.StudentDAOImpl$$EnhancerBySpringCGLIB$$56c74158.save(<generated>)
    at kz.nis.Main.main(Main.java:35)
Caused by: org.hibernate.exception.GenericJDBCException: could not execute batch
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:128)
    at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(BatchingBatch.java:104)
    at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(AbstractBatchImpl.java:147)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(JdbcCoordinatorImpl.java:212)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:633)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3283)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2479)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:98)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    ... 9 more
Caused by: java.sql.BatchUpdateException: Field 'student_id' doesn't have a default value
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.util.Util.handleNewInstance(Util.java:210)
    at com.mysql.cj.util.Util.getInstance(Util.java:185)
    at com.mysql.cj.util.Util.getInstance(Util.java:192)
    at com.mysql.cj.jdbc.exceptions.SQLError.createBatchUpdateException(SQLError.java:218)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchSerially(ClientPreparedStatement.java:864)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchInternal(ClientPreparedStatement.java:453)
    at com.mysql.cj.jdbc.StatementImpl.executeBatch(StatementImpl.java:839)
    at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:118)
    ... 26 more
Caused by: java.sql.SQLException: Field 'student_id' doesn't have a default value
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:127)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchSerially(ClientPreparedStatement.java:843)
    ... 29 more
Process finished with exit code 1
менял значение в sql_mode файле my.ini не помогает. 
Answer 1

Аннотации нужно указывать над переменной, а не над гетером. Заменить на:

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "student_id")
private Long studentID;
public Long getStudentID() {
    return studentID;
}
READ ALSO
О чистоте кода CSS

О чистоте кода CSS

В большинстве руководств, рекомендуют всем родительским елементам задавать классы, но при этом рекомендуют использовать не более двух селекторов...

162
Как правильно задать viewport

Как правильно задать viewport

Нужно чтоб страница до ширины 1200px уменьшалась пропорционально, а меньше этой ширины становилась адаптивной, как это можно реализовать?

187
Колонки таблицы равной ширины

Колонки таблицы равной ширины

Я создаю таблицу и выставляю в процентах ширину каждого столбцаДля примера, второй столбец должен иметь ширину в 30%, четвертый — 10%

172
Ошибка в html коде сайта

Ошибка в html коде сайта

Как устранить ошибку? Unchecked runtimelastError while running storage

178