最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring - How to upload a Image to my Postgres SQL? - Stack Overflow

programmeradmin4浏览0评论

I couldn't upload the image using hibernate in PostgreSQL, I was trying to learn how are images stored in the database but I had a problem while I was trying to store images. I also tried implementing a different code Ehcache but I'm still not able to send the image without caching, I'm getting a problem as there is no second-level cache:

ProductModel.java

@Entity
@Table(name="products")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class ProductModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "product_name", nullable = false)
    private String name;

    @Column(name = "description", length = 500)
    private String description;

    @Column(name = "price", nullable = false)
    private Long price;

    @Column(name = "stock", nullable = false)
    private Long stock;

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

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

    @Column(name = "count")
    private Long count;

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

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

    @Column(name="product_image_type")
    private List<String> productImageType;

    @Lob
    @Column(name="product_image")
    private List<byte[]> productImage;

    @Column(name="product_image_name")
    private List<String> productImageName;

    public ProductModel() {
    }

    public ProductModel(Long id, String name, String description, Long price, Long stock, String category, int discount, Long count, String brand, int rating, List<String> productImageType, List<byte[]> productImage, List<String> productImageName) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
        this.stock = stock;
        this.category = category;
        this.discount = discount;
        this.count = count;
        this.brand = brand;
        this.rating = rating;
        this.productImageType = productImageType;
        this.productImage = productImage;
        this.productImageName = productImageName;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Long getStock() {
        return stock;
    }

    public void setStock(Long stock) {
        this.stock = stock;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public List<String> getProductImageType() {
        return productImageType;
    }

    public void setProductImageType(List<String> productImageType) {
        this.productImageType = productImageType;
    }

    public List<byte[]> getProductImage() {
        return productImage;
    }

    public void setProductImage(List<byte[]> productImage) {
        this.productImage = productImage;
    }

    public List<String> getProductImageName() {
        return productImageName;
    }

    public void setProductImageName(List<String> productImageName) {
        this.productImageName = productImageName;
    }

    @Override
    public String toString() {
        return "ProductModel{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", stock=" + stock +
                ", category='" + category + '\'' +
                ", discount=" + discount +
                ", count=" + count +
                ", brand='" + brand + '\'' +
                ", rating=" + rating +
                ", productImageType=" + productImageType +
                ", productImage=" + productImage +
                ", productImageName=" + productImageName +
                '}';
    }
}

productController.java

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {

    private UserService userService;
    private ProductService productService;
    private PurchaseService purchaseService;

    public EmployeeController(UserService userService, ProductService productService, PurchaseService purchaseService) {
        this.userService = userService;
        this.productService = productService;
        this.purchaseService = purchaseService;
    }

    @PostMapping("/addNewProduct")
    public ResponseEntity<ProductModel> addProduct(@RequestPart("product_detail") ProductModel product
            , @RequestPart("product_images") MultipartFile[] imageData){
        return ResponseEntity.ok(productService.saveTheProduct(product,imageData));
    }


}

hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        ".0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:2427/test</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">kevin.2427</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.highlight_sql">true</property>
        <property name="hibernate.cache.use_second_level_cache" value="true" />
        <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.jcache.internal.JCacheRegionFactory" />
        <property name="hibernate.javax.cache.uri" value="ehcache.xml" />
        <property name="hibernate.javax.cache.provider" value="org.ehcache.jsr107.EhcacheCachingProvider" />
    </session-factory>
</hibernate-configuration>

I tried implementing Ehcache but there is a new internal server error as its configurations are wrong and I also got an error I also tried without it is giving me this error:

07-Feb-2025 19:24:36.466 INFO [http-nio-3000-exec-2]
 org.hibernate.cache.internal.RegionFactoryInitiator.initiateService HHH000026:
   Second-level cache disabled 07-Feb-2025 19:24:36.476 WARN [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH10001002:
   Using built-in connection pool (not intended for production use) 07-Feb-2025 19:24:36.551 WARN [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect HHH90000025:
   PostgreSQLDialect does not need to be specified explicitly using 'hibernate.dialect' (remove the property setting and it will be selected by default)
   07-Feb-2025 19:24:36.554 INFO [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService HHH10001005:
   Database info: Database JDBC URL [jdbc:postgresql://localhost:2427/test] Database driver: org.postgresql.Driver Database version: 17.0 Autocommit mode: false
   Isolation level: undefined/unknown Minimum pool size: 1 Maximum pool size: 20 

I couldn't upload the image using hibernate in PostgreSQL, I was trying to learn how are images stored in the database but I had a problem while I was trying to store images. I also tried implementing a different code Ehcache but I'm still not able to send the image without caching, I'm getting a problem as there is no second-level cache:

ProductModel.java

@Entity
@Table(name="products")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class ProductModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "product_name", nullable = false)
    private String name;

    @Column(name = "description", length = 500)
    private String description;

    @Column(name = "price", nullable = false)
    private Long price;

    @Column(name = "stock", nullable = false)
    private Long stock;

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

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

    @Column(name = "count")
    private Long count;

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

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

    @Column(name="product_image_type")
    private List<String> productImageType;

    @Lob
    @Column(name="product_image")
    private List<byte[]> productImage;

    @Column(name="product_image_name")
    private List<String> productImageName;

    public ProductModel() {
    }

    public ProductModel(Long id, String name, String description, Long price, Long stock, String category, int discount, Long count, String brand, int rating, List<String> productImageType, List<byte[]> productImage, List<String> productImageName) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
        this.stock = stock;
        this.category = category;
        this.discount = discount;
        this.count = count;
        this.brand = brand;
        this.rating = rating;
        this.productImageType = productImageType;
        this.productImage = productImage;
        this.productImageName = productImageName;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Long getStock() {
        return stock;
    }

    public void setStock(Long stock) {
        this.stock = stock;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public List<String> getProductImageType() {
        return productImageType;
    }

    public void setProductImageType(List<String> productImageType) {
        this.productImageType = productImageType;
    }

    public List<byte[]> getProductImage() {
        return productImage;
    }

    public void setProductImage(List<byte[]> productImage) {
        this.productImage = productImage;
    }

    public List<String> getProductImageName() {
        return productImageName;
    }

    public void setProductImageName(List<String> productImageName) {
        this.productImageName = productImageName;
    }

    @Override
    public String toString() {
        return "ProductModel{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", stock=" + stock +
                ", category='" + category + '\'' +
                ", discount=" + discount +
                ", count=" + count +
                ", brand='" + brand + '\'' +
                ", rating=" + rating +
                ", productImageType=" + productImageType +
                ", productImage=" + productImage +
                ", productImageName=" + productImageName +
                '}';
    }
}

productController.java

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {

    private UserService userService;
    private ProductService productService;
    private PurchaseService purchaseService;

    public EmployeeController(UserService userService, ProductService productService, PurchaseService purchaseService) {
        this.userService = userService;
        this.productService = productService;
        this.purchaseService = purchaseService;
    }

    @PostMapping("/addNewProduct")
    public ResponseEntity<ProductModel> addProduct(@RequestPart("product_detail") ProductModel product
            , @RequestPart("product_images") MultipartFile[] imageData){
        return ResponseEntity.ok(productService.saveTheProduct(product,imageData));
    }


}

hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:2427/test</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">kevin.2427</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.highlight_sql">true</property>
        <property name="hibernate.cache.use_second_level_cache" value="true" />
        <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.jcache.internal.JCacheRegionFactory" />
        <property name="hibernate.javax.cache.uri" value="ehcache.xml" />
        <property name="hibernate.javax.cache.provider" value="org.ehcache.jsr107.EhcacheCachingProvider" />
    </session-factory>
</hibernate-configuration>

I tried implementing Ehcache but there is a new internal server error as its configurations are wrong and I also got an error I also tried without it is giving me this error:

07-Feb-2025 19:24:36.466 INFO [http-nio-3000-exec-2]
 org.hibernate.cache.internal.RegionFactoryInitiator.initiateService HHH000026:
   Second-level cache disabled 07-Feb-2025 19:24:36.476 WARN [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH10001002:
   Using built-in connection pool (not intended for production use) 07-Feb-2025 19:24:36.551 WARN [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect HHH90000025:
   PostgreSQLDialect does not need to be specified explicitly using 'hibernate.dialect' (remove the property setting and it will be selected by default)
   07-Feb-2025 19:24:36.554 INFO [http-nio-3000-exec-2]

 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService HHH10001005:
   Database info: Database JDBC URL [jdbc:postgresql://localhost:2427/test] Database driver: org.postgresql.Driver Database version: 17.0 Autocommit mode: false
   Isolation level: undefined/unknown Minimum pool size: 1 Maximum pool size: 20 
Share Improve this question edited 2 days ago President James K. Polk 42k27 gold badges109 silver badges144 bronze badges asked Feb 7 at 14:41 K Kevin GladsonK Kevin Gladson 11 bronze badge 0
Add a comment  | 

1 Answer 1

Reset to default 0

First, what you read as an error message, is in fact just an info message.

To your question: I believe the BYTEA binary data type is the best option for storing images with Postgresql.

Documentation

  • Binary Data Types.
  • Storing Binary Data

Hence I believe the following column definition should work for you. Please note the change from List<byte[]> to just byte[].

    @Column(name="product_image", columnDefinition = "BYTEA")
    private byte[] productImage;

You will populate this field with file.getBytes().

I have a similar setup in one of my Spring Boot apps.

发布评论

评论列表(0)

  1. 暂无评论