【发布时间】:2020-03-18 00:14:23
【问题描述】:
我正在使用 Hibernate 开发这个 Spring Boot 应用程序。当我运行 Spring Boot 应用程序时,我不希望 Hibernate 在数据库或表已经存在时创建数据库或表。相反,我只希望它从现有数据库中获取数据或使用现有数据库向其中插入/更新数据。
application.properties
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
db.driver= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username = developer
spring.datasource.password = 111111
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Image.class
@Entity
@Table(name = "Image")
public class Image {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private Long imageNum;
@NotNull(message = "Product image id is required")
@Column(name = "ProductImgID")
private int productID;
@NotNull(message = "Image name is required")
@Column(name = "ImageUrl")
private String url;
Getter and Setter are below
}
BookRepository.class
@Repository
public interface BookRepository extends CrudRepository<Image, Long> {
}
BookService.class
@Service
public class BookService {
private BookRepository repository;
@Autowired
public BookService(BookRepository repository) {
this.repository = repository;
}
public List<Image> getImage() {
List<Image> img = (List<Image>) repository.findAll();
if (img.size() > 0) {
for (Image ig : img)
System.out.println(ig.toString());
return img;
}
return new ArrayList<>();
}
}
BookService.class
@Service
public class BookService {
private BookRepository repository;
@Autowired
public BookService(BookRepository repository) {
this.repository = repository;
}
public List<Image> getImage() {
List<Image> img = (List<Image>) repository.findAll();
if (img.size() > 0) {
for (Image ig : img)
System.out.println(ig.toString());
return img;
}
return new ArrayList<>();
}
}
**正如您在图像左侧看到的那样,当我运行应用程序时,它会自动添加其中没有数据的三列并将值返回给我。 **
当已经存在一个数据库、表或列时,如何让 Hibernate 创建另一个数据库、表或列?并且只是从数据库中获取现有数据?
【问题讨论】:
标签: java spring hibernate spring-boot thymeleaf