简体   繁体   中英

Store and retrive value from bit(2) column in mysql using java

I need to add values something like 0 - ACTIVE, 1 - INACTIVE, 2 - DISCHARGED

In my database and the column datatype I am using is bit(2) I am able to store it in database using enum

Here is my enum

public enum Status {
  ACTIVE,
  INACTIVE,
  DISCHARGED
}

I am able to store the value in database using Status.ACTIVE.ordinal() but not able to fetch the value from DB.

How can I fetch the value from database in java?

Quick answer: https://spring.io/guides/gs/accessing-data-jpa/

Full answer:

add jpa and mysql-connector dependency to your pom.xml file:

<!-- JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

After that, you should create interface (for example, SomeDataRepository), that extends CrudRepository.

public interface SomeDataRepository extends CrudRepository<Status, Integer> {
}

Then you fetching data from database becomes pretty easy (also as other work with db):

@Autowired
SomeDataRepository someDataRepository;
public List<Status> getData() {
    return someDataRepository.findAll();
}

To fetch the value of bit(2) column as integer from DB we need to use the CAST() function

SELECT CAST(colName AS unsigned int) as aliasName FROM tableName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM