java 连接Spring MVC到MySQL的问题

t3irkdon  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(128)

‘任务:
1.创建到数据库和架构的连接。启动应用程序。检查它是否完全工作。
1.创建一个带有String model和int series字段的Car实体,User将使用一对一关系引用这些字段。
1.将此类添加到休眠设置中。
1.用机器创建几个用户,将它们添加到数据库,然后将它们拉回来。
1.向服务中添加一个方法,该方法将使用HQL查询来获取拥有机器的用户(按其型号和系列)。
问题是,为我的一个朋友工作的代码只工作了一半

public static void main(String[] args) throws SQLException {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean(UserService.class);

        User user1 = new User("User1", "Lastname1", "user1@mail.ru");
        Car cfr1 = new Car("Mersedes", 1);
        user1.setCar(cfr1);
        userService.add(user1);

        User user11 = new User("User2", "Lastname2", "user22@mail.ru");
        Car cfr11 = new Car("BMW", 3);
        user11.setCar(cfr11);
        userService.add(user11);

        List<User> users = userService.listUsers();
        for (User user : users) {
            System.out.println("Id = " + user.getId());
            System.out.println("First Name = " + user.getFirstName());
            System.out.println("Last Name = " + user.getLastName());
            System.out.println("Email = " + user.getEmail());
            System.out.println("Car = " + user.getCar());
            System.out.println();
        }
        User user111 = userService.getUserByCar("BMW", 3);
        System.out.println("Владелец машины по модели и серии - " + user111);

        context.close();
    }

这是主要的

this is the db.properties file

# MySQL properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/test

db.username=root
db.password=12345

# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

这是一个例外
信息:HHH000400:使用方言:org.hibernate.dialect.MySQL8Dialect Hibernate:alter table汽车add constraint FKqw4c8e6nqrvy3ti1xj8w8wyc9 foreign key(user_id)references users(id)作者。04,2023 12:34:17 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException WARN:GenerationTarget遇到异常接受命令:通过JDBC语句org.hibernate.tool.schema.spi执行DDL“alter table汽车add constraint FKqw4c8e6nqrvy3ti1xj8w8wyc9 foreign key(user_id)references users(id)”时出错。CommandAcceptanceException:通过JDBC语句执行DDL“alter table汽车add constraint FKqw4c8e6nqrvy3ti1xj8w8wyc9 foreign key(user_id)references users(id)”时出错
应用程序配置

package hiber.config;

import hiber.model.Car;
import hiber.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScan(value = "hiber")
public class AppConfig {

   @Autowired
   private Environment env;

   @Bean
   public DataSource getDataSource() {
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(env.getProperty("db.driver"));
      dataSource.setUrl(env.getProperty("db.url"));
      dataSource.setUsername(env.getProperty("db.username"));
      dataSource.setPassword(env.getProperty("db.password"));
      return dataSource;
   }

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
      factoryBean.setDataSource(getDataSource());

      Properties props = new Properties();
      props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
      props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setAnnotatedClasses(User.class, Car.class);
      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}

车辆等级

package hiber.model;

import javax.persistence.*;

@Entity
@Table(name = "cars")
public class Car {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "model")
    private String model;

    @Column(name = "series")
    private int series;

    @OneToOne
    @JoinColumn(name = "user_id",referencedColumnName = "id")
    private User user;

    public Car(){

    }

    public Car(String model, int series) {
        this.model = model;
        this.series = series;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getSeries() {
        return series;
    }

    public void setSeries(int series) {
        this.series = series;
    }

    public User getUser() {
        return user;
    }

    public User setUser(User user) {
        this.user = user;
        return user;
    }

    @Override
    public String toString() {
        return "Car {" +
                "id=" + id +
                ", model='" + model + '\'' +
                ", series=" + series +
                '}';
    }
}

类用户

package hiber.model;

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "email")
   private String email;

   @OneToOne(mappedBy = "user")
   private Car car;

   public User() {}
   
   public User(String firstName, String lastName, String email) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;
   }

   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   public Car getCar(){return car;}

   public Car setCar(Car car){
      this.car =car;
      return car;
   }

   @Override
   public String toString() {
      return "User{" +
              "id=" + id +
              ", firstName='" + firstName + '\'' +
              ", lastName='" + lastName + '\'' +
              ", email='" + email + '\'' +
              '}';
   }
}
s4chpxco

s4chpxco1#

您的表的id和user_id列似乎由于某种原因具有不兼容的类型。请参考此问题以获取可能的答案:MySQL cannot create foreign key constraint

mwkjh3gx

mwkjh3gx2#

在你的汽车实体中

//change 
  @OneToOne
    @JoinColumn(name = "user_id",referencedColumnName = "id")
    private User user;
//to
@OneToOne(cascade = CascadeType.ALL)
private User user;

并在用户实体中进行如下更改

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
   private Car car;

如果问题仍然存在,请尝试删除数据库并创建一个新的数据库。然后运行该程序。

相关问题